def _get_failure_from_exception(
            e: BaseException) -> TransactionResult.Failure:
        """
        Gets `Failure` from an exception
        :param e: exception
        :return: a Failure
        """

        try:
            if isinstance(e, IconServiceBaseException):
                if e.code >= ExceptionCode.SCORE_ERROR or isinstance(
                        e, IconScoreException):
                    Logger.warning(e.message, ICON_SERVICE_LOG_TAG)
                else:
                    Logger.exception(e.message, ICON_SERVICE_LOG_TAG)

                code = int(e.code)
                message = str(e.message)
            else:
                Logger.exception(e, ICON_SERVICE_LOG_TAG)
                Logger.error(e, ICON_SERVICE_LOG_TAG)

                code: int = ExceptionCode.SYSTEM_ERROR.value
                message = str(e)
        except:
            code: int = ExceptionCode.SYSTEM_ERROR.value
            message = 'Invalid exception: code or message is invalid'

        return TransactionResult.Failure(code, message)
示例#2
0
文件: engine.py 项目: bccenter/SSI
    def _commit_claim(self, context: 'IconScoreContext', iscore: int):
        address: 'Address' = context.tx.origin
        block: 'Block' = context.block
        tx: 'Transaction' = context.tx
        success = True

        try:
            icx: int = self._iscore_to_icx(iscore)

            from_account: 'Account' = context.storage.icx.get_account(
                context, address)
            treasury_address: 'Address' = context.storage.icx.fee_treasury
            treasury_account: 'Account' = context.storage.icx.get_account(
                context, treasury_address)

            treasury_account.withdraw(icx)
            from_account.deposit(icx)
            context.storage.icx.put_account(context, treasury_account)
            context.storage.icx.put_account(context, from_account)

        except BaseException as e:
            Logger.exception(tag=_TAG, msg=str(e))
            success = False
            raise e
        finally:
            self._reward_calc_proxy.commit_claim(success, address,
                                                 block.height, block.hash,
                                                 tx.index, tx.hash)
示例#3
0
    async def dispatch(request: 'SanicRequest', channel_name: str = ""):
        req_json = request.json
        url = request.url
        channel = channel_name if channel_name else StubCollection().conf[ConfigKey.CHANNEL]

        context = {
            "url": url,
            "channel": channel,
        }

        response: Union[Response, DictResponse, BatchResponse]
        try:
            client_ip = request.remote_addr if request.remote_addr else request.ip
            Logger.info(f'rest_server_v3 request with {req_json}', DISPATCH_V3_TAG)
            Logger.info(f"{client_ip} requested {req_json} on {url}")

            validate_jsonschema_v3(request=req_json)
        except GenericJsonRpcServerError as e:
            response = ApiErrorResponse(id=req_json.get('id', 0),
                                        code=e.code,
                                        message=str(e),
                                        http_status=e.http_status,
                                        debug=False)
        except Exception as e:
            Logger.exception(e)
            response = ExceptionResponse(e, id=req_json.get('id', 0), debug=False)
        else:
            response = await async_dispatch(request.body, methods, context=context)
        Logger.info(f'rest_server_v3 with response {response}', DISPATCH_V3_TAG)
        return sanic_response.json(response.deserialized(), status=response.http_status, dumps=json.dumps)
    def _get_failure_from_exception(
            e: BaseException) -> TransactionResult.Failure:
        """
        Gets `Failure` from an exception
        :param e: exception
        :return: a Failure
        """

        if isinstance(e, IconServiceBaseException):
            if e.code == ExceptionCode.SCORE_ERROR or isinstance(
                    e, ScoreErrorException):
                Logger.warning(e.message, ICON_SERVICE_LOG_TAG)
            else:
                Logger.exception(e.message, ICON_SERVICE_LOG_TAG)

            code = e.code
            message = e.message
        else:
            Logger.exception(e, ICON_SERVICE_LOG_TAG)
            Logger.error(e, ICON_SERVICE_LOG_TAG)

            code = ExceptionCode.SERVER_ERROR
            message = str(e)

        return TransactionResult.Failure(code, message)
    def run(self, context: 'IconScoreContext'):
        Logger.info(tag=TAG, msg="UnstakePatcher.run() start")

        storage = context.storage.icx

        for target in self._targets:
            try:
                address = target.address
                coin_part = storage.get_part(context, AccountPartFlag.COIN,
                                             address)
                stake_part = storage.get_part(context, AccountPartFlag.STAKE,
                                              address)

                result: Result = self._check_removable(coin_part, stake_part,
                                                       target)
                if result == Result.FALSE:
                    self._add_failure_item(target)
                else:
                    if result == Result.REMOVABLE_V0:
                        stake_part = self._remove_invalid_expired_unstakes_v0(
                            stake_part, target)
                    else:
                        stake_part = self._remove_invalid_expired_unstakes_v1(
                            stake_part, target)

                    assert stake_part.is_dirty()
                    storage.put_stake_part(context, address, stake_part)
                    self._emit_event_log(context, target)
                    self._add_success_item(target)
            except BaseException as e:
                # Although some unexpected errors happen, keep going
                Logger.exception(tag=TAG, msg=str(e))

        Logger.info(tag=TAG, msg="UnstakePatcher.run() end")
示例#6
0
    def _deploy_score(context: 'IconScoreContext',
                      score_name: str,
                      score_address: 'Address',
                      builtin_score_owner: 'Address'):
        score_deploy_storage: IconScoreDeployStorage = \
            context.icon_score_deploy_engine.icon_deploy_storage

        score_source_path_in_iconservice: str = os.path.join(
            IconBuiltinScoreLoader._pre_builtin_score_root_path(), score_name)

        # Save deploy_info for a builtin score to score_deploy_storage.
        deploy_info = IconScoreDeployInfo(
            score_address=score_address,
            deploy_state=DeployState.ACTIVE,
            owner=builtin_score_owner,
            current_tx_hash=ZERO_TX_HASH,
            next_tx_hash=ZERO_TX_HASH)
        score_deploy_storage.put_deploy_info(context, deploy_info)

        tx_hash: bytes = deploy_info.current_tx_hash

        # score_path is score_root_path/score_address/ directory.
        score_path: str = os.path.join(
            context.score_root_path, score_address.to_bytes().hex())

        # Make a directory for a builtin score with a given score_address.
        os.makedirs(score_path, exist_ok=True)

        try:
            score_deploy_path: str = os.path.join(score_path, f'0x{tx_hash.hex()}')

            # remove_path() supports directory as well as file.
            remove_path(score_deploy_path)
            # Copy builtin score source files from iconservice package to score_deploy_path.
            copytree(score_source_path_in_iconservice, score_deploy_path)
        except FileExistsError:
            pass

        try:
            # Import score class from deployed builtin score sources
            score_info: 'IconScoreInfo' =\
                IconScoreContextUtil.create_score_info(context, score_address, tx_hash)

            # Create a score instance from the imported score class.
            score = score_info.create_score()

            # Call on_install() to initialize the score database of the builtin score.
            score.on_install()
        except BaseException as e:
            Logger.exception(
                f'Failed to deploy a builtin score: {score_address}\n{str(e)}',
                ICON_DEPLOY_LOG_TAG)
            raise e
    def write_result(self, path: str):
        Logger.info(tag=TAG,
                    msg=f"UnstakePatcher.write_result() start: {path}")

        total_unstake = self._success_unstake + self._failure_unstake

        Logger.info(
            tag=TAG,
            msg="Invalid expired unstakes management result: "
            f"total_unstake={total_unstake} "
            f"success_unstake={self._success_unstake} "
            f"failure_unstake={self._failure_unstake} "
            f"total_items={len(self._targets)} "
            f"success_items={len(self._success_targets)} "
            f"failure_items={len(self._failure_targets)}",
        )

        try:
            report = {
                # Unstake amount
                "total_unstake":
                total_unstake,
                "success_unstake":
                self._success_unstake,
                "failure_unstake":
                self._failure_unstake,

                # Item count
                "total":
                len(self._targets),
                "success":
                len(self._success_targets),
                "failure":
                len(self._failure_targets),

                # Item list
                "success_targets":
                [target.to_dict() for target in self._success_targets],
                "failure_targets":
                [target.to_dict() for target in self._failure_targets],
            }

            with open(path, "w") as f:
                text = json.dumps(report, indent=4)
                f.write(text)
        except BaseException as e:
            Logger.exception(tag=TAG, msg=str(e))

        Logger.info(tag=TAG, msg=f"UnstakePatcher.write_result() end")
    def _charge_transaction_fee(self, context: 'IconScoreContext',
                                params: dict, status: int,
                                step_used: int) -> (int, int):
        """Charge a fee to from account
        Because it is on finalizing a transaction,
        this method MUST NOT throw any exceptions

        Assume that from account can charge a failed tx fee

        :param params:
        :param status: 1: SUCCESS, 0: FAILURE
        :return: final step_used, step_price
        """
        version: int = params.get('version', 2)
        from_: 'Address' = params['from']

        step_price = context.step_counter.step_price

        if version < 3:
            # Support coin transfer based on protocol v2
            # 0.01 icx == 10**16 loop
            # FIXED_FEE(0.01 icx) == step_used(10**6) * step_price(10**10)
            step_used = 10**6

            if status == TransactionResult.FAILURE:
                # protocol v2 does not charge a fee for a failed tx
                step_price = 0
            elif IconScoreContextUtil.is_service_flag_on(
                    context, IconServiceFlag.FEE):
                # 0.01 icx == 10**16 loop
                # FIXED_FEE(0.01 icx) == step_used(10**6) * step_price(10**10)
                step_price = 10**10

        # Charge a fee to from account
        fee: int = step_used * step_price
        try:
            self._icx_engine.charge_fee(context, from_, fee)
        except BaseException as e:
            if hasattr(e, 'message'):
                message = e.message
            else:
                message = str(e)
            Logger.exception(message, ICON_SERVICE_LOG_TAG)
            step_used = 0

        # final step_used and step_price
        return step_used, step_price
示例#9
0
    def serve(self, config: 'IconConfig'):
        async def _serve():
            await self._inner_service.connect(exclusive=True)
            Logger.info(f'Start IconService Service serve!', ICON_SERVICE)

        channel = config[ConfigKey.CHANNEL]
        amqp_key = config[ConfigKey.AMQP_KEY]
        amqp_target = config[ConfigKey.AMQP_TARGET]
        score_root_path = config[ConfigKey.SCORE_ROOT_PATH]
        db_root_path = config[ConfigKey.STATE_DB_ROOT_PATH]

        self._set_icon_score_stub_params(channel, amqp_key, amqp_target)

        Logger.info(f'==========IconService Service params==========',
                    ICON_SERVICE)
        Logger.info(f'score_root_path : {score_root_path}', ICON_SERVICE)
        Logger.info(f'icon_score_state_db_root_path  : {db_root_path}',
                    ICON_SERVICE)
        Logger.info(f'amqp_target  : {amqp_target}', ICON_SERVICE)
        Logger.info(f'amqp_key  :  {amqp_key}', ICON_SERVICE)
        Logger.info(f'icon_score_queue_name  : {self._icon_score_queue_name}',
                    ICON_SERVICE)
        Logger.info(f'==========IconService Service params==========',
                    ICON_SERVICE)

        # Before creating IconScoreInnerService instance,
        # loop SHOULD be set as a current event loop for the current thread.
        # Otherwise connection between iconservice and rc will be failed.
        loop = MessageQueueService.loop
        asyncio.set_event_loop(loop)

        try:
            self._inner_service = IconScoreInnerService(
                amqp_target, self._icon_score_queue_name, conf=config)
        except FatalException as e:
            Logger.exception(e, ICON_EXCEPTION_LOG_TAG)
            Logger.error(e, ICON_EXCEPTION_LOG_TAG)
            self._inner_service.clean_close()
        finally:
            Logger.debug(
                "icon service will be closed while open the icon service engine. "
                "check if the config is valid")

        loop.create_task(_serve())
        loop.add_signal_handler(signal.SIGINT, self.close)
        loop.add_signal_handler(signal.SIGTERM, self.close)

        try:
            loop.run_forever()
        except FatalException as e:
            Logger.exception(e, ICON_EXCEPTION_LOG_TAG)
            Logger.error(e, ICON_EXCEPTION_LOG_TAG)
            self._inner_service.clean_close()
        finally:
            """
            If the function is called when the operation is not an endless loop 
            in an asynchronous function, the await is terminated immediately.
            """
            Logger.debug("loop has been stopped and will be closed")
            loop.run_until_complete(loop.shutdown_asyncgens())
            loop.close()
示例#10
0
 def _log_exception(self,
                    e: BaseException,
                    tag: str = ICON_INNER_LOG_TAG) -> None:
     Logger.exception(e, tag)
     Logger.error(e, tag)
示例#11
0
 def _log_exception(e: BaseException, tag: str) -> None:
     Logger.exception(str(e), tag)
     Logger.error(str(e), tag)
示例#12
0
 def test_exception(self):
     Logger.exception('exception log')
     Logger.exception('exception log', TAG)
示例#13
0
 def test_exception(self):
     try:
         raise Exception()
     except:
         Logger.exception(TAG, 'exception log')