def __polling_to_private_chain(self, purchase_transaction):
     try:
         if PrivateChainUtil.is_transaction_completed(purchase_transaction):
             return 'done'
         return 'doing'
     except (SendTransactionError, ReceiptError) as e:
         logging.info(e)
         return 'fail'
Beispiel #2
0
 def test_is_transaction_completed_ok_last(self):
     with patch('requests.post') as mock_post:
         mock_post.side_effect = [
             FakeResponse(status_code=200, text='{}'),
             FakeResponse(status_code=200, text='{}'),
             FakeResponse(status_code=200, text='{}'),
             FakeResponse(status_code=200, text='{}'),
             FakeResponse(status_code=200, text='{"result": {"logs": [{"type": "mined"}]}}')
         ]
         tran = '0x1234567890123456789012345678901234567890'
         response = PrivateChainUtil.is_transaction_completed(transaction=tran)
         self.assertEqual(response, True)
         self.assertEqual(mock_post.call_count, settings.TRANSACTION_CONFIRM_COUNT)
Beispiel #3
0
    def exec_main_proc(self):
        ################
        # get parameter
        ################
        sort_key = TimeUtil.generate_sort_key()
        from_user_eth_address = self.event['requestContext']['authorizer'][
            'claims']['custom:private_eth_address']
        user_id = self.event['requestContext']['authorizer']['claims'][
            'cognito:username']
        allowance = PrivateChainUtil.get_allowance(from_user_eth_address)
        transaction_count = PrivateChainUtil.get_transaction_count(
            from_user_eth_address)

        ################
        # validation
        ################
        # validate raw_transaction
        # init_approve_signed_transaction
        if int(allowance, 16) != 0:
            # allowance が設定されている場合は必須
            if self.params.get('init_approve_signed_transaction') is None:
                raise ValidationError(
                    'init_approve_signed_transaction is invalid.')
            # data
            init_approve_data = PrivateChainUtil.get_data_from_raw_transaction(
                self.params['init_approve_signed_transaction'],
                transaction_count)
            PrivateChainUtil.validate_erc20_approve_data(init_approve_data)
            if int(init_approve_data[72:], 16) != 0:
                raise ValidationError('Value of init_approve is invalid.')
            transaction_count = PrivateChainUtil.increment_transaction_count(
                transaction_count)

        # approve_signed_transaction
        approve_data = PrivateChainUtil.get_data_from_raw_transaction(
            self.params['approve_signed_transaction'], transaction_count)
        PrivateChainUtil.validate_erc20_approve_data(approve_data)
        # 日次の限度額を超えていた場合は例外
        sum_price = self.__get_token_send_value_today(user_id)
        if Decimal(os.environ['DAILY_LIMIT_TOKEN_SEND_VALUE']
                   ) < sum_price + Decimal(int(approve_data[72:], 16)):
            raise ValidationError('Token withdrawal limit has been exceeded.')
        transaction_count = PrivateChainUtil.increment_transaction_count(
            transaction_count)

        # relay_signed_transaction
        relay_data = PrivateChainUtil.get_data_from_raw_transaction(
            self.params['relay_signed_transaction'], transaction_count)
        PrivateChainUtil.validate_erc20_relay_data(relay_data)
        # approve と relay の value が同一であること
        approve_value = int(approve_data[72:], 16)
        relay_value = int(relay_data[72:], 16)
        if approve_value != relay_value:
            raise ValidationError('approve and relay values do not match.')

        #######################
        # send_raw_transaction
        #######################
        # 既に approve されている場合(allowance の戻り値が 0 ではない場合)、該当の approve を削除する(0 で更新)
        if int(allowance, 16) != 0:
            PrivateChainUtil.send_raw_transaction(
                self.params.get('init_approve_signed_transaction'))

        # approve 実施
        approve_transaction_hash = PrivateChainUtil.send_raw_transaction(
            self.params.get('approve_signed_transaction'))
        self.__create_send_info_with_approve_transaction_hash(
            sort_key, user_id, approve_transaction_hash, relay_value)

        # token_send_table への書き込み完了後に出金関連の例外が発生した場合は、token_send_table のステータスを fail に更新する
        try:
            # relay 実施
            relay_transaction_hash = PrivateChainUtil.send_raw_transaction(
                self.params.get('relay_signed_transaction'))
            self.__update_send_info_with_relay_transaction_hash(
                sort_key, user_id, relay_transaction_hash)
            # transaction の完了を確認
            is_completed = PrivateChainUtil.is_transaction_completed(
                relay_transaction_hash)
        except SendTransactionError as e:
            # ステータスを fail に更新し中断
            self.__update_send_info_with_send_status(sort_key, user_id, 'fail')
            raise e
        except ReceiptError:
            # send_value の値が残高を超えた場合や、処理最小・最大値の範囲に収まっていない場合に ReceiptError が発生するため
            # ValidationError として処理を中断する
            # ステータスを fail に更新
            self.__update_send_info_with_send_status(sort_key, user_id, 'fail')
            raise ValidationError('send_value')

        # transaction が完了していた場合、ステータスを done に更新
        if is_completed:
            self.__update_send_info_with_send_status(sort_key, user_id, 'done')

        return {
            'statusCode': 200,
            'body': json.dumps({'is_completed': is_completed})
        }
    def exec_main_proc(self):
        ################
        # get parameter
        ################
        # article info
        article_info_table = self.dynamodb.Table(
            os.environ['ARTICLE_INFO_TABLE_NAME'])
        article_info = article_info_table.get_item(
            Key={
                'article_id': self.params['article_id']
            }).get('Item')
        # eth_address
        from_user_eth_address = self.event['requestContext']['authorizer'][
            'claims']['custom:private_eth_address']
        to_user_eth_address = UserUtil.get_private_eth_address(
            self.cognito, article_info['user_id'])
        # transaction_count
        transaction_count = PrivateChainUtil.get_transaction_count(
            from_user_eth_address)

        ################
        # validation
        ################
        # does not tip same user
        if article_info['user_id'] == self.event['requestContext'][
                'authorizer']['claims']['cognito:username']:
            raise ValidationError('Can not tip to myself')

        # validate raw_transaction
        # tip
        tip_data = PrivateChainUtil.get_data_from_raw_transaction(
            self.params['tip_signed_transaction'], transaction_count)
        PrivateChainUtil.validate_erc20_transfer_data(tip_data,
                                                      to_user_eth_address)
        # burn
        transaction_count = PrivateChainUtil.increment_transaction_count(
            transaction_count)
        burn_data = PrivateChainUtil.get_data_from_raw_transaction(
            self.params['burn_signed_transaction'], transaction_count)
        PrivateChainUtil.validate_erc20_transfer_data(
            burn_data, '0x' + os.environ['BURN_ADDRESS'])

        # burn 量が正しいこと
        tip_value = int(tip_data[72:], 16)
        burn_value = int(burn_data[72:], 16)
        calc_burn_value = int(Decimal(tip_value) / Decimal(10))
        if burn_value != calc_burn_value:
            raise ValidationError('burn_value is invalid.')

        # 残高が足りていること
        if not self.__is_burnable_user(from_user_eth_address, tip_value,
                                       burn_value):
            raise ValidationError('Required at least {token} token'.format(
                token=tip_value + burn_value))

        #######################
        # send_raw_transaction
        #######################
        transaction_hash = PrivateChainUtil.send_raw_transaction(
            self.params['tip_signed_transaction'])
        burn_transaction = None
        try:
            # 投げ銭が成功した時のみバーン処理を行う
            if PrivateChainUtil.is_transaction_completed(transaction_hash):
                # バーンのトランザクション処理
                burn_transaction = PrivateChainUtil.send_raw_transaction(
                    self.params['burn_signed_transaction'])
            else:
                logging.info(
                    'Burn was not executed because tip transaction was uncompleted.'
                )
        except Exception as err:
            logging.fatal(err)
            traceback.print_exc()
        finally:
            # create tip info
            self.__create_tip_info(transaction_hash, tip_value,
                                   burn_transaction, article_info)

        return {'statusCode': 200}
Beispiel #5
0
 def test_is_transaction_completed_ok(self):
     tran = '0x1234567890123456789012345678901234567890'
     response = PrivateChainUtil.is_transaction_completed(transaction=tran)
     self.assertEqual(response, True)
Beispiel #6
0
 def test_is_transaction_completed_ng_exists_not_mined_type(self):
     with self.assertRaises(ReceiptError):
         tran = '0x1234567890123456789012345678901234567890'
         PrivateChainUtil.is_transaction_completed(transaction=tran)
Beispiel #7
0
 def test_is_transaction_completed_ng_not_exists_result(self):
     tran = '0x1234567890123456789012345678901234567890'
     response = PrivateChainUtil.is_transaction_completed(transaction=tran)
     self.assertEqual(response, False)
    def exec_main_proc(self):
        from_user_eth_address = self.event['requestContext']['authorizer'][
            'claims']['custom:private_eth_address']
        recipient_eth_address = self.params['recipient_eth_address']
        send_value = self.params['send_value']
        sort_key = TimeUtil.generate_sort_key()
        user_id = self.event['requestContext']['authorizer']['claims'][
            'cognito:username']

        # 日次の限度額を超えていた場合は例外
        sum_price = self.__get_token_send_value_today(user_id)
        if Decimal(os.environ['DAILY_LIMIT_TOKEN_SEND_VALUE']
                   ) < sum_price + Decimal(send_value):
            raise ValidationError('Token withdrawal limit has been exceeded.')

        # allowance を取得
        allowance = self.__get_allowance(from_user_eth_address)
        # transaction_count を取得
        transaction_count = self.__get_transaction_count(from_user_eth_address)
        # 既に approve されている場合(allowance の戻り値が "0x0" ではない場合)、該当の approve を削除する(0 で更新)
        if allowance != '0x0':
            self.__approve(from_user_eth_address, 0, transaction_count)
            transaction_count = self.__increment_transaction_count(
                transaction_count)

        # approve 実施
        approve_transaction_hash = self.__approve(from_user_eth_address,
                                                  send_value,
                                                  transaction_count)
        transaction_count = self.__increment_transaction_count(
            transaction_count)
        self.__create_send_info_with_approve_transaction_hash(
            sort_key, user_id, approve_transaction_hash)

        # token_send_table への書き込み完了後に出金関連の例外が発生した場合は、token_send_table のステータスを fail に更新する
        try:
            # relay 実施
            relay_transaction_hash = self.__relay(from_user_eth_address,
                                                  recipient_eth_address,
                                                  send_value,
                                                  transaction_count)
            self.__update_send_info_with_relay_transaction_hash(
                sort_key, user_id, relay_transaction_hash)
            # transaction の完了を確認
            is_completed = PrivateChainUtil.is_transaction_completed(
                relay_transaction_hash)
        except SendTransactionError as e:
            # ステータスを fail に更新し中断
            self.__update_send_info_with_send_status(sort_key, user_id, 'fail')
            raise e
        except ReceiptError:
            # send_value の値が残高を超えた場合や、処理最小・最大値の範囲に収まっていない場合に ReceiptError が発生するため
            # ValidationError として処理を中断する
            # ステータスを fail に更新
            self.__update_send_info_with_send_status(sort_key, user_id, 'fail')
            raise ValidationError('send_value')

        # transaction が完了していた場合、ステータスを done に更新
        if is_completed:
            self.__update_send_info_with_send_status(sort_key, user_id, 'done')

        return {
            'statusCode': 200,
            'body': json.dumps({'is_completed': is_completed})
        }