Пример #1
0
    def test_get_put_delete_deposit(self):
        context = self.context

        deposit = Deposit()
        deposit.id = create_tx_hash()
        deposit.score_address = create_address(AddressPrefix.CONTRACT)
        deposit.sender = create_address(AddressPrefix.EOA)
        deposit.deposit_amount = 10000
        deposit.deposit_used = 10000
        deposit.created = 10
        deposit.expires = 1000000
        deposit.virtual_step_issued = 100000000000
        deposit.virtual_step_used = 200000000000
        deposit.prev_id = create_tx_hash()
        deposit.next_id = create_tx_hash()
        deposit.version = 2
        self.storage.put_deposit(context, deposit)

        deposit2 = self.storage.get_deposit(context, deposit.id)
        self.assertEqual(deposit, deposit2)
        self.assertEqual(deposit.id, deposit2.id)

        self.storage.delete_deposit(context, deposit.id)
        deposit2 = self.storage.get_deposit(context, deposit.id)
        self.assertIsNone(deposit2)
    def setUp(self):
        db = Mock(spec=IconScoreDatabase)
        db.address = create_address(AddressPrefix.CONTRACT)
        context = IconScoreContext()
        traces = Mock(spec=list)

        context.tx = Mock(spec=Transaction)
        context.block = Mock(spec=Block)
        context.cumulative_step_used = Mock(spec=int)
        context.cumulative_step_used.attach_mock(Mock(), '__add__')
        context.step_counter = Mock(spec=IconScoreStepCounter)
        context.event_logs = Mock(spec=list)
        context.logs_bloom = Mock(spec=BloomFilter)
        context.traces = traces

        ContextContainer._push_context(context)
        context.icon_score_manager = Mock()
        context.icon_score_manager.get_owner = Mock(return_value=None)
        context.icon_score_manager.get_tx_hashes_by_score_address = \
            Mock(return_value=(create_tx_hash(), create_tx_hash()))
        context.internal_call = InternalCall(context)
        context.internal_call._other_score_call = Mock()
        context.internal_call.icx_engine = Mock(spec=IcxEngine)
        context.icon_score_mapper = Mock()
        context.icon_score_mapper.get_icon_score = Mock(
            return_value=TestScore(db))
        context.internal_call._validate_score_blacklist = Mock(
            return_value=False)
        self._score = TestScore(db)
Пример #3
0
def test_get_put_delete_deposit(context, storage):
    context = context

    deposit = Deposit()
    deposit.id = create_tx_hash()
    deposit.score_address = create_address(AddressPrefix.CONTRACT)
    deposit.sender = create_address(AddressPrefix.EOA)
    deposit.deposit_amount = 10000
    deposit.deposit_used = 10000
    deposit.created = 10
    deposit.expires = 1000000
    deposit.virtual_step_issued = 100000000000
    deposit.virtual_step_used = 200000000000
    deposit.prev_id = create_tx_hash()
    deposit.next_id = create_tx_hash()
    deposit.version = 2
    storage.put_deposit(context, deposit)

    deposit2 = storage.get_deposit(context, deposit.id)
    assert deposit == deposit2
    assert deposit.id == deposit2.id

    storage.delete_deposit(context, deposit.id)
    deposit2 = storage.get_deposit(context, deposit.id)
    assert deposit2 is None
Пример #4
0
def test_to_dict():
    """
    - Checks if Deposit.to_dict method makes the object to dict type correctly.
    - Checks if Deposit.to_dict method makes the object to dict type as casing like camel case correctly.
    """
    deposit = Deposit()
    deposit.id = create_tx_hash()
    deposit.score_address = create_address(AddressPrefix.CONTRACT)
    deposit.sender = create_address(AddressPrefix.EOA)
    deposit.deposit_amount = 10000
    deposit.deposit_used = 10000
    deposit.created = 10
    deposit.expires = 1000000
    deposit.virtual_step_issued = 100000000000
    deposit.virtual_step_used = 200000000000
    deposit.prev_id = create_tx_hash()
    deposit.next_id = create_tx_hash()

    deposit_in_dict = deposit.to_dict()
    assert isinstance(deposit_in_dict, dict)

    deposit_in_dict_to_camel_case = deposit.to_dict(to_camel_case)
    assert isinstance(deposit_in_dict_to_camel_case, dict)

    attributes = dir(deposit)
    cnt_attr = 0
    for attr in attributes:
        if attr in Deposit._EXPOSING_ITEM_KEYS:
            assert attr in deposit_in_dict
            assert to_camel_case(attr) in deposit_in_dict_to_camel_case
            cnt_attr += 1
    assert len(Deposit._EXPOSING_ITEM_KEYS) == cnt_attr
    def test_install(self):
        # Case when the user install SCORE first time.
        tx_hash1 = create_tx_hash()
        self.deployer.deploy(self.address,
                             self.read_zipfile_as_byte(self.archive_path),
                             tx_hash1)
        converted_tx_hash = f'0x{bytes.hex(tx_hash1)}'
        install_path = os.path.join(self.score_root_path, converted_tx_hash)
        zip_file_info_gen = self.deployer._extract_files_gen(
            self.read_zipfile_as_byte(self.archive_path))
        file_path_list = [name for name, info, parent_dir in zip_file_info_gen]

        installed_contents = []
        for directory, dirs, filename in os.walk(install_path):
            parent_directory_index = directory.rfind('/')
            parent_dir_name = directory[parent_directory_index + 1:]
            for file in filename:
                if parent_dir_name == f'0x{bytes.hex(tx_hash1)}':
                    installed_contents.append(file)
                else:
                    installed_contents.append(f'{parent_dir_name}/{file}')
        self.assertEqual(True, os.path.exists(install_path))
        self.assertTrue(installed_contents.sort() == file_path_list.sort())

        # Case when the user install SCORE second time.
        with self.assertRaises(BaseException) as e:
            self.deployer.deploy(self.address,
                                 self.read_zipfile_as_byte(self.archive_path),
                                 tx_hash1)
        self.assertEqual(e.exception.code, ExceptionCode.INVALID_PARAMS)

        # Case when installing SCORE with badzipfile Data.
        tx_hash2 = create_tx_hash()
        with self.assertRaises(BaseException) as e:
            self.deployer.deploy(self.address,
                                 self.read_zipfile_as_byte(self.archive_path2),
                                 tx_hash2)
        self.assertEqual(e.exception.code, ExceptionCode.INVALID_PARAMS)
        converted_tx_hash = f'0x{bytes.hex(tx_hash2)}'
        install_path2 = os.path.join(self.score_root_path, converted_tx_hash)
        self.assertFalse(os.path.exists(install_path2))

        # Case when The user specifies an installation path that does not have permission.
        with self.assertRaises(BaseException) as e:
            self.deployer2.deploy(self.address,
                                  self.read_zipfile_as_byte(self.archive_path),
                                  tx_hash1)
        self.assertIsInstance(e.exception, PermissionError)

        # Case when the user try to install scores without directories.
        tx_hash3 = create_tx_hash()
        converted_tx_hash = f'0x{bytes.hex(tx_hash3)}'
        self.deployer.deploy(self.address,
                             self.read_zipfile_as_byte(self.archive_path3),
                             tx_hash3)
        install_path3 = os.path.join(self.score_root_path, converted_tx_hash)
        self.assertEqual(True, os.path.exists(install_path3))
Пример #6
0
    def test_install(self):
        self.normal_score_path = os.path.join(DIRECTORY_PATH, 'sample',
                                              'normal_score.zip')
        self.bad_zip_file_path = os.path.join(DIRECTORY_PATH, 'sample',
                                              'badzipfile.zip')
        self.inner_dir_path = os.path.join(DIRECTORY_PATH, 'sample',
                                           'innerdir.zip')

        # Case when the user install SCORE first time.
        tx_hash1 = create_tx_hash()
        score_deploy_path: str = get_score_deploy_path(self.score_root_path,
                                                       self.address, tx_hash1)

        IconScoreDeployer.deploy(
            score_deploy_path,
            self.read_zipfile_as_byte(self.normal_score_path))
        self.assertEqual(True, os.path.exists(score_deploy_path))

        zip_file_info_gen = IconScoreDeployer._extract_files_gen(
            self.read_zipfile_as_byte(self.normal_score_path))
        file_path_list = [name for name, info, parent_dir in zip_file_info_gen]

        installed_contents = self.get_installed_files(score_deploy_path)
        self.assertTrue(self.check_package_json_validity(installed_contents))
        installed_contents.sort()
        file_path_list.sort()
        self.assertEqual(installed_contents, file_path_list)

        # Case when installing SCORE with bad-zip-file Data.
        tx_hash2 = create_tx_hash()
        score_deploy_path: str = get_score_deploy_path(self.score_root_path,
                                                       self.address, tx_hash2)

        with self.assertRaises(BaseException) as e:
            IconScoreDeployer.deploy(
                score_deploy_path,
                self.read_zipfile_as_byte(self.bad_zip_file_path))
        self.assertEqual(e.exception.code, ExceptionCode.INVALID_PACKAGE)
        self.assertTrue(os.path.exists(score_deploy_path))

        # Case when the user specifies an installation path that does not have permission.
        score_deploy_path: str = get_score_deploy_path('/', self.address,
                                                       tx_hash1)
        with self.assertRaises(BaseException) as e:
            IconScoreDeployer.deploy(
                score_deploy_path,
                self.read_zipfile_as_byte(self.normal_score_path))
        # On MacOS OSError is raised which is different from Linux
        # self.assertIsInstance(e.exception, PermissionError)

        # Case when the user try to install scores inner directories.
        tx_hash3 = create_tx_hash()
        score_deploy_path: str = get_score_deploy_path(self.score_root_path,
                                                       self.address, tx_hash3)
        IconScoreDeployer.deploy(
            score_deploy_path, self.read_zipfile_as_byte(self.inner_dir_path))
        self.assertEqual(True, os.path.exists(score_deploy_path))
    def test_get_deploy_tx_params(self):
        context = Mock(spec=IconScoreContext)

        tx_hash = create_tx_hash()
        self.storage._create_db_key = Mock(return_value=tx_hash)
        self.storage._db.get = Mock(return_value=None)
        self.assertEqual(None, self.storage.get_deploy_tx_params(context, tx_hash))

        tx_hash = create_tx_hash()
        tx_params = IconScoreDeployTXParams(tx_hash, DeployType.INSTALL, create_address(1), {})
        self.storage._create_db_key = Mock(return_value=tx_hash)
        self.storage._db.get = Mock(return_value=tx_params.to_bytes())

        self.assertEqual(tx_params.to_bytes(), self.storage.get_deploy_tx_params(context, tx_hash).to_bytes())
Пример #8
0
    def test_deposit_meta_from_bytes_to_bytes(self):
        deposit_meta = DepositMeta()
        deposit_meta.head_id = create_tx_hash()
        deposit_meta.tail_id = create_tx_hash()
        deposit_meta.available_head_id_of_deposit = create_tx_hash()
        deposit_meta.available_head_id_of_virtual_step = create_tx_hash()
        deposit_meta.expires_of_deposit = 1
        deposit_meta.expires_of_virtual_step = 200
        deposit_meta.version = 3

        deposit_meta_in_bytes = deposit_meta.to_bytes()
        self.assertIsInstance(deposit_meta_in_bytes, bytes)

        deposit_meta_2 = DepositMeta.from_bytes(deposit_meta_in_bytes)
        self.assertIsInstance(deposit_meta_2, DepositMeta)
        self.assertEqual(deposit_meta, deposit_meta_2)
 def test_remove_existing_score(self):
     tx_hash = create_tx_hash()
     converted_tx_hash = f'0x{bytes.hex(tx_hash)}'
     install_path = os.path.join(self.score_root_path, converted_tx_hash)
     self.deployer.deploy(self.address, self.read_zipfile_as_byte(self.archive_path), tx_hash)
     self.deployer.remove_existing_score(install_path)
     self.assertFalse(os.path.exists(install_path))
Пример #10
0
    def _make_invalid_deploy_tx(self,
                        addr_from: 'Address',
                        addr_to: 'Address',
                        content: Any = None):

        deploy_params = {}
        deploy_data = {'contentType': 'application/zip', 'content': content, 'params': deploy_params}

        timestamp_us = create_timestamp()
        nonce = 0

        request_params = {
            "version": self._version,
            "from": addr_from,
            "to": addr_to,
            "stepLimit": self._step_limit,
            "timestamp": timestamp_us,
            "nonce": nonce,
            "signature": self._signature,
            "dataType": "deploy",
            "data": deploy_data
        }

        method = 'icx_sendTransaction'
        # Insert txHash into request params
        request_params['txHash'] = create_tx_hash()
        tx = {
            'method': method,
            'params': request_params
        }

        return tx
    def test_invoke_v3_without_fee(self):
        block_height = 1
        block_hash = create_block_hash()
        block_timestamp = 0
        tx_hash = create_tx_hash()
        value = 1 * 10**18

        tx_v3 = {
            'method': 'icx_sendTransaction',
            'params': {
                'version': 3,
                'from': self._genesis_address,
                'to': self._to,
                'value': value,
                'stepLimit': 20000,
                'timestamp': 1234567890,
                'txHash': tx_hash
            }
        }

        block = Block(block_height, block_hash, block_timestamp,
                      self.genesis_block.hash)

        tx_results, state_root_hash = self._engine.invoke(block, [tx_v3])
        self.assertIsInstance(state_root_hash, bytes)
        self.assertEqual(len(state_root_hash), 32)

        self.assertEqual(len(tx_results), 1)

        tx_result: 'TransactionResult' = tx_results[0]
        self.assertIsNone(tx_result.failure)
        self.assertIsNone(tx_result.score_address)
        self.assertEqual(tx_result.status, 1)
        self.assertEqual(tx_result.block_height, block_height)
        self.assertEqual(tx_result.block_hash, block_hash)
        self.assertEqual(tx_result.tx_index, 0)
        self.assertEqual(tx_result.tx_hash, tx_hash)

        # step_used MUST BE 10**6 on protocol v2
        step_unit = self._engine._step_counter_factory.get_step_cost(
            StepType.DEFAULT)

        self.assertEqual(tx_result.step_used, step_unit)

        step_price = self._engine._get_step_price()
        if self._engine._is_flag_on(IconServiceFlag.fee):
            # step_used MUST BE 10**10 on protocol v2
            self.assertEqual(step_price, 10**10)
        else:
            self.assertEqual(step_price, 0)
        self.assertEqual(tx_result.step_price, step_price)

        self._engine.commit(block)

        # Check whether fee charging works well
        from_balance: int = \
            self._engine._icx_engine.get_balance(None, self.from_)
        fee = tx_result.step_price * tx_result.step_used
        self.assertEqual(fee, 0)
        self.assertEqual(from_balance, self._total_supply - value - fee)
    def test_internal_transfer_step(self):
        tx_hash = bytes.hex(create_tx_hash())
        from_ = create_address(AddressPrefix.EOA)
        to_ = create_address(AddressPrefix.CONTRACT)

        request = create_request([ReqData(tx_hash, from_, to_, 'call', {})])

        # noinspection PyUnusedLocal
        def intercept_invoke(*args, **kwargs):
            ContextContainer._push_context(args[0])
            context_db = self._inner_task._icon_service_engine._icx_context_db
            score = SampleScore(IconScoreDatabase(to_, context_db))
            score.transfer()

        score_engine_invoke = Mock(side_effect=intercept_invoke)
        self._inner_task._icon_service_engine._validate_score_blacklist = Mock(
        )
        self._inner_task._icon_service_engine. \
            _icon_score_engine.invoke = score_engine_invoke

        self._inner_task._icon_service_engine._icon_score_mapper.get_icon_score = Mock(
            return_value=None)
        result = self._inner_task._invoke(request)
        score_engine_invoke.assert_called()

        self.assertEqual(result['txResults'][tx_hash]['status'], '0x1')

        call_args_list = self.step_counter.apply_step.call_args_list
        self.assertEqual(call_args_list[0][0], (StepType.DEFAULT, 1))
        self.assertEqual(call_args_list[1][0], (StepType.INPUT, 0))
        self.assertEqual(call_args_list[2][0], (StepType.CONTRACT_CALL, 1))
        self.assertEqual(call_args_list[3][0], (StepType.CONTRACT_CALL, 1))
        self.assertEqual(len(call_args_list), 4)
Пример #13
0
    def create_message_tx(self,
                          from_: Union['EOAAccount', 'Address', None],
                          to_: Union['EOAAccount', 'Address', 'MalformedAddress'],
                          data: bytes = None,
                          value: int = 0) -> dict:

        addr_from: Optional['Address'] = self._convert_address_from_address_type(from_)
        addr_to: Optional['Address', 'MalformedAddress'] = self._convert_address_from_address_type(to_)

        timestamp_us = create_timestamp()
        nonce = 0

        request_params = {
            "version": self._version,
            "from": addr_from,
            "to": addr_to,
            "value": value,
            "stepLimit": DEFAULT_BIG_STEP_LIMIT,
            "timestamp": timestamp_us,
            "nonce": nonce,
            "signature": self._signature,
            "dataType": "message",
            "data": '0x' + data.hex(),
        }

        method = 'icx_sendTransaction'
        # Inserts txHash into request params
        request_params['txHash'] = create_tx_hash()
        tx = {
            'method': method,
            'params': request_params
        }

        self.icon_service_engine.validate_transaction(tx)
        return tx
    def _make_message_tx(self,
                         addr_from: Union['Address', None],
                         addr_to: 'Address',
                         data: bytes = None,
                         value: int = 0):
        timestamp_us = create_timestamp()
        nonce = 0

        request_params = {
            "version": self._version,
            "from": addr_from,
            "to": addr_to,
            "value": value,
            "stepLimit": self._step_limit,
            "timestamp": timestamp_us,
            "nonce": nonce,
            "signature": self._signature,
            "dataType": "message",
            "data": '0x' + data.hex(),
        }

        method = 'icx_sendTransaction'
        # Inserts txHash into request params
        request_params['txHash'] = create_tx_hash()
        tx = {
            'method': method,
            'params': request_params
        }

        self.icon_service_engine.validate_transaction(tx)
        return tx
Пример #15
0
def test_get_put_delete_score_fee(context, storage):
    score_address = create_address(AddressPrefix.CONTRACT)

    deposit_meta = DepositMeta()
    deposit_meta.head_id = create_tx_hash()
    deposit_meta.tail_id = create_tx_hash()
    deposit_meta.available_head_id_of_deposit = create_tx_hash()
    deposit_meta.available_head_id_of_virtual_step = create_tx_hash()
    storage.put_deposit_meta(context, score_address, deposit_meta)

    deposit_meta_2 = storage.get_deposit_meta(context, score_address)
    assert deposit_meta == deposit_meta_2

    storage.delete_deposit_meta(context, score_address)
    deposit_meta_2 = storage.get_deposit_meta(context, score_address)
    assert deposit_meta_2 is None
Пример #16
0
    def _create_invalid_deploy_tx(self,
                                  from_: Union['EOAAccount', 'Address', None],
                                  to_: Union['EOAAccount', 'Address'],
                                  content: Any = None):
        addr_from: Optional['Address'] = self._convert_address_from_address_type(from_)
        addr_to: 'Address' = self._convert_address_from_address_type(to_)

        deploy_params: dict = {}
        deploy_data: dict = {'contentType': 'application/zip', 'content': content, 'params': deploy_params}

        timestamp_us: int = create_timestamp()
        nonce: int = 0

        request_params = {
            "version": self._version,
            "from": addr_from,
            "to": addr_to,
            "stepLimit": DEFAULT_DEPLOY_STEP_LIMIT,
            "timestamp": timestamp_us,
            "nonce": nonce,
            "signature": self._signature,
            "dataType": "deploy",
            "data": deploy_data
        }

        method = 'icx_sendTransaction'
        # Insert txHash into request params
        request_params['txHash'] = create_tx_hash()
        tx = {
            'method': method,
            'params': request_params
        }

        return tx
    def test_tx_params_from_bytes_to_bytes(self):
        tx_hash1 = create_tx_hash()
        score_address = create_address(1)
        deploy_state = DeployType.INSTALL
        data_params = {
            "contentType": "application/zip",
            "content":
            "0x1867291283973610982301923812873419826abcdef91827319263187263a7326e",
            "params": {
                "name": "ABCToken",
                "symbol": "abc",
                "decimals": "0x12"
            }
        }

        tx_params1 = IconScoreDeployTXParams(tx_hash1, deploy_state,
                                             score_address, data_params)

        data = IconScoreDeployTXParams.to_bytes(tx_params1)
        self.assertTrue(isinstance(data, bytes))

        tx_params2 = IconScoreDeployTXParams.from_bytes(data)
        self.assertEqual(tx_params2.tx_hash, tx_hash1)
        self.assertEqual(tx_params2.deploy_type, deploy_state)
        self.assertEqual(tx_params2._score_address, score_address)
        self.assertEqual(tx_params2.deploy_data, data_params)
Пример #18
0
    def _genesis_invoke(self) -> dict:
        tx_hash = create_tx_hash()
        timestamp_us = create_timestamp()
        request_params = {
            'txHash': tx_hash,
            'version': self._version,
            'timestamp': timestamp_us
        }

        tx = {
            'method': 'icx_sendTransaction',
            'params': request_params,
            'genesisData': {
                "accounts": [{
                    "name": "genesis",
                    "address": self._genesis,
                    "balance": 100 * self._icx_factor
                }, {
                    "name": "fee_treasury",
                    "address": self._fee_treasury,
                    "balance": 0
                }]
            },
        }

        block_hash = create_block_hash()
        block = Block(self._block_height, block_hash, timestamp_us, None)
        invoke_response: dict = self.icon_service_engine.invoke(block, [tx])
        self.icon_service_engine.commit(block)
        self._block_height += 1
        self._prev_block_hash = block_hash

        return invoke_response
Пример #19
0
    def test_invoke_v2_without_fee(self):
        block_height = 1
        block_hash = create_block_hash()
        block_timestamp = 0
        tx_hash = create_tx_hash()
        value = 1 * 10 ** 18

        tx_v2 = {
            'method': 'icx_sendTransaction',
            'params': {
                'from': self.from_,
                'to': self._to,
                'value': value,
                'fee': 10 ** 16,
                'timestamp': 1234567890,
                'txHash': tx_hash
            }
        }

        block = Block(block_height,
                      block_hash,
                      block_timestamp,
                      self.genesis_block.hash,
                      0)

        tx_results, state_root_hash, _, _ = self._engine.invoke(block, [tx_v2])
        self.assertIsInstance(state_root_hash, bytes)
        self.assertEqual(len(state_root_hash), 32)
        self.assertEqual(len(tx_results), 1)

        tx_result: 'TransactionResult' = tx_results[0]
        self.assertIsNone(tx_result.failure)
        self.assertIsNone(tx_result.score_address)
        self.assertEqual(tx_result.status, 1)
        self.assertEqual(tx_result.block_height, block_height)
        self.assertEqual(tx_result.block_hash, block_hash)
        self.assertEqual(tx_result.tx_index, 0)
        self.assertEqual(tx_result.tx_hash, tx_hash)

        # step_used MUST BE 10 ** 6 on protocol v2
        self.assertEqual(tx_result.step_used, 10**6)

        step_price = self._engine._step_counter_factory.get_step_price()
        # if self._engine._is_flag_on(IconServiceFlag.fee):
        #     # step_used MUST BE 10**10 on protocol v2
        #     self.assertEqual(step_price, 10 ** 10)
        # else:
        #     self.assertEqual(step_price, 0)
        self.assertEqual(tx_result.step_price, step_price)

        # Write updated states to levelDB
        self._engine.commit(block.height, block.hash, None)

        # Check whether fee charging works well
        context = _create_context(IconScoreContextType.DIRECT)
        from_balance: int = IconScoreContext.engine.icx.get_balance(
            context, self.from_)
        fee = tx_result.step_price * tx_result.step_used
        self.assertEqual(fee, 0)
        self.assertEqual(from_balance, self._total_supply - value - fee)
Пример #20
0
    def test_message_step(self):
        self._inner_task._icon_service_engine._validate_score_blacklist = Mock(
        )

        tx_hash1 = bytes.hex(create_tx_hash())
        from_ = create_address(AddressPrefix.EOA)
        to_ = from_
        # data size 25
        data = '0x01234abcde01234abcde01234abcde01234abcde01234abcde'

        request = create_request([
            ReqData(tx_hash1, from_, to_, 'message', data),
        ])

        result = self._inner_task_invoke(request)
        self.assertEqual(result['txResults'][tx_hash1]['status'], '0x1')

        input_length = 25

        self.assertEqual(self.step_counter.apply_step.call_args_list[0][0],
                         (StepType.DEFAULT, 1))
        self.assertEqual(self.step_counter.apply_step.call_args_list[1][0],
                         (StepType.INPUT, input_length))
        self.assertEqual(len(self.step_counter.apply_step.call_args_list), 2)

        step_used = self._calc_step_used(0, 2)

        self._assert_step_used(step_used, request, tx_hash1)
    def create_deploy_score_tx(self,
                               score_root: str,
                               score_name: str,
                               from_: Union['EOAAccount', 'Address', None],
                               to_: Union['EOAAccount', 'Address'],
                               deploy_params: dict = None,
                               timestamp_us: int = None,
                               data: bytes = None,
                               is_sys: bool = False,
                               pre_validation_enabled: bool = True,
                               step_limit: int = DEFAULT_DEPLOY_STEP_LIMIT) -> dict:

        addr_from: Optional['Address'] = self._convert_address_from_address_type(from_)
        addr_to: 'Address' = self._convert_address_from_address_type(to_)

        if deploy_params is None:
            deploy_params = {}

        score_path = get_score_path(score_root, score_name)

        if is_sys:
            deploy_data = {'contentType': 'application/tbears', 'content': score_path, 'params': deploy_params}
        else:
            if data is None:
                mz = InMemoryZip()
                mz.zip_in_memory(score_path)
                data = f'0x{mz.data.hex()}'
            else:
                data = f'0x{bytes.hex(data)}'
            deploy_data = {'contentType': 'application/zip', 'content': data, 'params': deploy_params}

        if timestamp_us is None:
            timestamp_us = create_timestamp()
        nonce = 0

        request_params = {
            "version": self._version,
            "from": addr_from,
            "to": addr_to,
            "stepLimit": step_limit,
            "timestamp": timestamp_us,
            "nonce": nonce,
            "signature": self._signature,
            "dataType": "deploy",
            "data": deploy_data
        }

        origin_params = {'params': self.make_origin_params(request_params)}
        method = 'icx_sendTransaction'
        # Insert txHash into request params
        request_params['txHash'] = create_tx_hash()
        tx = {
            'method': method,
            'params': request_params
        }

        if pre_validation_enabled:
            self.icon_service_engine.validate_transaction(tx, origin_params)

        return tx
Пример #22
0
    def test_deploy_raise_no_package_above_revision3(self):
        """
        if package doesn't contain package.json, raise exception(no package.json) above revision 3
        """
        zip_list = ['nodir_nopackage.zip', 'normal_nopackage.zip']

        for zip_item in zip_list:
            address: 'Address' = create_address(AddressPrefix.CONTRACT)
            self.archive_path = os.path.join(DIRECTORY_PATH, 'sample',
                                             zip_item)
            tx_hash1 = create_tx_hash()
            score_deploy_path: str = get_score_deploy_path(
                self.score_root_path, address, tx_hash1)

            with self.assertRaises(BaseException) as e:
                IconScoreDeployer.deploy(
                    score_deploy_path,
                    self.read_zipfile_as_byte(self.archive_path),
                    Revision.THREE.value)
            self.assertEqual(e.exception.code, ExceptionCode.INVALID_PACKAGE)
            self.assertEqual(e.exception.message, "package.json not found")
            self.assertTrue(os.path.exists(score_deploy_path))

            score_path: str = get_score_path(self.score_root_path, address)
            remove_path(score_path)
Пример #23
0
    def test_deploy_when_score_depth_is_different(self):
        """
        Reads all files from the depth lower than where the file 'package.json' is
        and test deploying successfully.
        """
        zip_list = ['score_registry.zip', 'fakedir.zip', 'nodir.zip']

        for zip_item in zip_list:
            address: 'Address' = create_address(AddressPrefix.CONTRACT)
            self.archive_path = os.path.join(DIRECTORY_PATH, 'sample',
                                             zip_item)
            tx_hash1 = create_tx_hash()
            score_deploy_path: str = get_score_deploy_path(
                self.score_root_path, address, tx_hash1)

            IconScoreDeployer.deploy(
                score_deploy_path,
                self.read_zipfile_as_byte(self.archive_path))
            self.assertEqual(True, os.path.exists(score_deploy_path))

            zip_file_info_gen = IconScoreDeployer._extract_files_gen(
                self.read_zipfile_as_byte(self.archive_path))
            file_path_list = [
                name for name, info, parent_dir in zip_file_info_gen
            ]

            installed_contents = self.get_installed_files(score_deploy_path)
            self.assertTrue(
                self.check_package_json_validity(installed_contents))
            installed_contents.sort()
            file_path_list.sort()
            self.assertEqual(installed_contents, file_path_list)

            score_path: str = get_score_path(self.score_root_path, address)
            remove_path(score_path)
Пример #24
0
    def test_deploy_when_score_depth_is_different_above_revision3(self):
        """
        Reads all files from the depth lower than where the file 'package.json' is
        and test deploying successfully.
        """
        zip_list = [('score_registry.zip', [
            'interfaces/__init__.py', 'interfaces/abc_owned.py',
            'interfaces/abc_score_registry.py', 'package.json',
            'score_registry/__init__.py', 'score_registry/score_registry.py',
            'utility/__init__.py', 'utility/owned.py', 'utility/utils.py'
        ]), ('fakedir.zip', ['__init__.py', 'call_class1.py', 'package.json']),
                    ('nodir.zip',
                     ['__init__.py', 'package.json', 'sample_token.py'])]

        for zip_file, expected_list in zip_list:
            address: 'Address' = create_address(AddressPrefix.CONTRACT)
            self.archive_path = os.path.join(DIRECTORY_PATH, 'sample',
                                             zip_file)
            tx_hash1 = create_tx_hash()
            score_deploy_path: str = get_score_deploy_path(
                self.score_root_path, address, tx_hash1)

            IconScoreDeployer.deploy(
                score_deploy_path,
                self.read_zipfile_as_byte(self.archive_path),
                Revision.THREE.value)
            self.assertEqual(True, os.path.exists(score_deploy_path))

            installed_files = self.get_installed_files(score_deploy_path)
            installed_files.sort()
            self.assertEqual(installed_files, expected_list)

            score_path: str = get_score_path(self.score_root_path, address)
            remove_path(score_path)
Пример #25
0
    def _genesis_invoke(self) -> dict:
        tx_hash = create_tx_hash()
        timestamp_us = create_timestamp()
        request_params = {
            'txHash': tx_hash,
            'version': self._version,
            'timestamp': timestamp_us
        }

        tx = {
            'method': 'icx_sendTransaction',
            'params': request_params,
            'genesisData': {
                "accounts": [{
                    "name": "genesis",
                    "address": self._genesis,
                    "balance": 100 * self._icx_factor
                }, {
                    "name": "fee_treasury",
                    "address": self._fee_treasury,
                    "balance": 0
                }, {
                    "name": "_admin",
                    "address": self._admin,
                    "balance": 1_000_000 * self._icx_factor
                }]
            },
        }
Пример #26
0
    def _make_icx_send_tx(self,
                          addr_from: Optional['Address'],
                          addr_to: Union['Address', 'MalformedAddress'],
                          value: int,
                          disable_pre_validate: bool = False,
                          support_v2: bool = False):

        timestamp_us = create_timestamp()
        nonce = 0

        request_params = {
            "from": addr_from,
            "to": addr_to,
            "value": value,
            "stepLimit": self._step_limit,
            "timestamp": timestamp_us,
            "nonce": nonce,
            "signature": self._signature
        }

        if support_v2:
            request_params["fee"] = 10**16
        else:
            request_params["version"] = self._version

        method = 'icx_sendTransaction'
        # Insert txHash into request params
        request_params['txHash'] = create_tx_hash()
        tx = {'method': method, 'params': request_params}

        if not disable_pre_validate:
            self.icon_service_engine.validate_transaction(tx)
        return tx
Пример #27
0
    def _make_score_call_tx(self,
                            addr_from: Optional['Address'],
                            addr_to: 'Address',
                            method: str,
                            params: dict,
                            value: int = 0):

        timestamp_us = create_timestamp()
        nonce = 0

        request_params = {
            "version": self._version,
            "from": addr_from,
            "to": addr_to,
            "value": value,
            "stepLimit": self._step_limit,
            "timestamp": timestamp_us,
            "nonce": nonce,
            "signature": self._signature,
            "dataType": "call",
            "data": {
                "method": method,
                "params": params
            }
        }

        method = 'icx_sendTransaction'
        # Insert txHash into request params
        request_params['txHash'] = create_tx_hash()
        tx = {'method': method, 'params': request_params}

        self.icon_service_engine.validate_transaction(tx)
        return tx
Пример #28
0
    def test_commit_change_block_hash(self):
        block_height = 1
        self._to = create_address(AddressPrefix.CONTRACT)
        instant_block_hash = create_block_hash()
        block_timestamp = 0
        tx_hash = create_tx_hash()

        dummy_tx = {
            'method': 'icx_sendTransaction',
            'params': {
                'nid': 3,
                'version': 3,
                'from': self._admin.address,
                'to': self._to,
                'value': 1 * 10**18,
                'stepLimit': 1000000,
                'timestamp': 1234567890,
                'txHash': tx_hash
            }
        }
        block = Block(block_height, instant_block_hash, block_timestamp,
                      self.genesis_block.hash, 0)

        self.icon_service_engine.invoke(block, [dummy_tx])
        instant_block_hash = block.hash
        block_hash = create_block_hash()
        self.icon_service_engine.commit(block.height, instant_block_hash,
                                        block_hash)

        self.assertEqual(self.icon_service_engine._get_last_block().hash,
                         block_hash)
        self.assertEqual(IconScoreContext.storage.icx.last_block.hash,
                         block_hash)
Пример #29
0
    def test_request(self, score_invoke):
        inner_task = generate_inner_task(3)
        IconScoreContext.engine.prep.preps = Mock()

        # noinspection PyUnusedLocal
        def intercept_invoke(*args, **kwargs):
            ContextContainer._push_context(args[0])

            context_db = inner_task._icon_service_engine._icx_context_db

            score_address = create_address(AddressPrefix.CONTRACT, b'address')
            score = SampleScore(IconScoreDatabase(score_address, context_db))

            address = create_address(AddressPrefix.EOA, b'address')
            score.SampleEvent(b'i_data', address, 10, b'data', 'text')

            ContextContainer._pop_context()

        score_invoke.side_effect = intercept_invoke

        from_ = create_address(AddressPrefix.EOA, b'from')
        to_ = create_address(AddressPrefix.CONTRACT, b'score')

        request = create_request([
            ReqData(bytes.hex(create_tx_hash(b'tx1')), from_, to_, 0, 'call',
                    {}),
            ReqData(bytes.hex(create_tx_hash(b'tx2')), from_, to_, 0, 'call',
                    {})
        ])
        response = inner_task._invoke(request)

        step_total = 0

        for tx_hash in response['txResults'].keys():
            result = response['txResults'][tx_hash]
            step_total += int(result['stepUsed'], 16)
            self.assertIn('status', result)
            self.assertIn('txHash', result)
            self.assertIn('txIndex', result)
            self.assertIn('blockHeight', result)
            self.assertIn('blockHash', result)
            self.assertIn('cumulativeStepUsed', result)
            self.assertIn('stepUsed', result)
            self.assertEqual(1, len(result['eventLogs']))
            self.assertEqual(step_total, int(result['cumulativeStepUsed'], 16))

        clear_inner_task()
Пример #30
0
    def test_score_invoke_failure_by_readonly_external_call(self):
        block_height = 1
        block_hash = create_block_hash()
        block_timestamp = 0
        tx_hash = create_tx_hash()
        value = 0
        to = self._governance_address

        step_limit = 200000000
        tx_v3 = {
            'method': 'icx_sendTransaction',
            'params': {
                'txHash':
                tx_hash,
                'nid':
                3,
                'version':
                3,
                'from':
                self._admin.address,
                'to':
                to,
                'value':
                value,
                'stepLimit':
                step_limit,
                'timestamp':
                1234567890,
                'dataType':
                'call',
                'data': {
                    'method': 'getScoreStatus',
                    'params': {
                        'txHash': tx_hash
                    }
                },
                'signature':
                'VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA='
            }
        }

        block = Block(block_height, block_hash, block_timestamp,
                      self.genesis_block.hash, 0)

        tx_results, state_root_hash, _, _, is_shutdown = self.icon_service_engine.invoke(
            block, [tx_v3])
        self.assertIsInstance(state_root_hash, bytes)
        self.assertEqual(len(state_root_hash), 32)
        self.assertFalse(is_shutdown)
        self.assertEqual(len(tx_results), 1)

        tx_result: 'TransactionResult' = tx_results[0]
        self.assertIsNotNone(tx_result.failure)
        self.assertIsNone(tx_result.score_address)
        self.assertEqual(tx_result.status, 0)
        self.assertEqual(tx_result.block_height, block_height)
        self.assertEqual(tx_result.block_hash, block_hash)
        self.assertEqual(tx_result.tx_index, 0)
        self.assertEqual(tx_result.tx_hash, tx_hash)