Example #1
0
    def post(self, request):

        serializer_input = addresses.NewAddressesPostParametersSerializer(data=request.DATA)

        if serializer_input.is_valid():
            currency = serializer_input.data["currency"]
            wallet = serializer_input.data["wallet"]
            btc_rpc_call = BTCRPCCall(wallet=wallet, currency=currency)
            #check is on testnet or not.
            is_test_net = constantutil.check_service_is_test_net(btc_rpc_call)

            logger.info("quantity is " + str(serializer_input.data["quantity"]) + ".")
            new_addresses = []
            for x in xrange(0, int(serializer_input.data[attributeConst.QUANTITY])):
                new_address = btc_rpc_call.do_get_new_address()
                btc_rpc_call.do_set_account(new_address, new_address)
                new_addresses.append(new_address)

            new_addresses_response = addresses.NewAddresses(addresses=new_addresses, test=is_test_net)

            addresses_serializer = addresses.NewAddressesSerializer(data=new_addresses_response.__dict__)
            if addresses_serializer.is_valid():
                return Response(addresses_serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(addresses_serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)
        return Response(serializer_input.errors, status=status.HTTP_400_BAD_REQUEST)
Example #2
0
    def __init__(self):

        self.yml_config = ConfigFileReader()
        self.fee = self.yml_config.get_reserved_fee_for_transferring(
            currency='btc')
        self.confirms = self.yml_config.get_min_transfer_confirmations(
            currency='btc')
        self.btc_rpc_call = BTCRPCCall(wallet='receive', currency='btc')
        self.coin_to_be_send_dict = self.__init_dict_of_accounts()
    def post(self, request):
        log.info(request.DATA)
        post_serializers = check_multi_receives.PostParametersSerializer(data=request.DATA)
        btc_rpc_call = BTCRPCCall()
        is_test_net = constantutil.check_service_is_test_net(btc_rpc_call)

        response_list = []
        if post_serializers.is_valid():
            log.info(post_serializers.data["transactions"])
            transactions = post_serializers.data["transactions"]
            for transaction in transactions:
                log.info(transaction)

                address_validation = btc_rpc_call.do_validate_address(address=transaction["address"])

                if address_validation["isvalid"] is False:
                    return Response(
                        transaction["address"] + " is not a valid address", status=status.HTTP_400_BAD_REQUEST
                    )

                received_with_risk = self.__receive_amount_for_risk(
                    wallet_address=transaction["address"],
                    expected_amount=transaction["amount"],
                    btc_service=btc_rpc_call,
                )
                tx_ids = self.__get_txIds(transaction["address"], btc_service=btc_rpc_call)
                log.info(tx_ids)
                log.info(Decimal(received_with_risk["result"]))
                response = check_multi_receives.ReceiveInformationResponse(
                    currency=transaction["currency"],
                    address=transaction["address"],
                    received=Decimal(received_with_risk["result"]),
                    risk=received_with_risk["risk"],
                    txs=tx_ids,
                )

                response_list.append(response.__dict__)

            receives_response = check_multi_receives.ReceivesInformationResponse(
                receives=response_list, test=is_test_net
            )
            response_dict = receives_response.__dict__

            response_serializer = check_multi_receives.ReceivesInformationResponseSerializer(data=response_dict)

            if response_serializer.is_valid():
                return Response(response_serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(response_serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)

        return Response(post_serializers.errors, status=status.HTTP_400_BAD_REQUEST)
Example #4
0
    def __init__(self):

        self.yml_config = ConfigFileReader()
        self.fee = self.yml_config.get_reserved_fee_for_transferring(currency='btc')
        self.confirms = self.yml_config.get_min_transfer_confirmations(currency='btc')
        self.btc_rpc_call = BTCRPCCall(wallet='receive', currency='btc')
        self.coin_to_be_send_dict = self.__init_dict_of_accounts()
Example #5
0
    def post(self, request):
        post_serializers = wallet_balance.GetWalletBalancePostParameterSerializer(data=request.DATA)

        wallet_balance_response_list = []
        if post_serializers.is_valid():
            currency = post_serializers.data["currency"]
            wallet_list = yml_config.get_wallet_list(currency)
            log.info(wallet_list)

            for wallet in wallet_list:
                log.info(wallet)
                btc_rpc_call = BTCRPCCall(wallet=wallet, currency=currency)
                is_test_net = constantutil.check_service_is_test_net(btc_rpc_call)
                log.info(is_test_net)

                balance = btc_rpc_call.get_wallet_balance()
                log.info(format(balance, '0.8f'))

                wallet_balance_response = wallet_balance.WalletBalanceResponse(wallet=wallet,
                                                                               balance=Decimal(balance),
                                                                               test=is_test_net)

                log.info(wallet_balance_response.__dict__)
                wallet_balance_response_list.append(wallet_balance_response.__dict__)

            wallets_balance_response = wallet_balance.WalletsBalanceResponse(wallets=wallet_balance_response_list)

            wallets_balance_response_serializer = \
                wallet_balance.WalletsBalanceResponseSerializer(data=wallets_balance_response.__dict__)

            if wallets_balance_response_serializer.is_valid():
                return Response(wallets_balance_response_serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(wallets_balance_response_serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)

        return Response(post_serializers.errors, status=status.HTTP_400_BAD_REQUEST)
Example #6
0
    def post(self, request):

        serializer = send.SendFromPostParametersSerializer(data=request.DATA)

        #from_account_balance = btc_rpc_call.get_balance(account=serializer)

        if serializer.is_valid():

            currency = serializer.data["currency"]
            btc_rpc_call = BTCRPCCall(wallet=serializer.data["wallet"], currency=currency)
             #check is testnet or not
            is_test_net = constantutil.check_service_is_test_net(btc_rpc_call)

            from_account = serializer.data["fromAddress"]
            to_address = serializer.data["toAddress"]
            fee_limit = serializer.data["feeLimit"]
            send_amount = serializer.data["amount"]

            balance = btc_rpc_call.get_balance(account=from_account)

            from_account_is_valid = (btc_rpc_call.do_validate_address(address=from_account))["isvalid"]
            to_address_is_valid = (btc_rpc_call.do_validate_address(address=to_address))["isvalid"]

            if not from_account_is_valid:
                response_serializer = self.__send_to(send_status="NOK",
                                                     message="invalid send from address %s" % from_account,
                                                     test=is_test_net)
                return Response(data=response_serializer.data, status=status.HTTP_406_NOT_ACCEPTABLE)

            if not to_address_is_valid:
                response_serializer = self.__send_to(send_status="NOK",
                                                     message="invalid send to address %s" % to_address,
                                                     test=is_test_net)
                return Response(data=response_serializer.data, status=status.HTTP_406_NOT_ACCEPTABLE)

            if (send_amount + fee_limit) > balance:
                response_serializer = self.__send_to(send_status="NOK",
                                                     message="There is no enough fund from %s" % from_account,
                                                     test=is_test_net)
                return Response(data=response_serializer.data, status=status.HTTP_406_NOT_ACCEPTABLE)

            try:
                send_response_tx_id = btc_rpc_call.send_from(from_account=from_account,
                                                             to_address=to_address, amount=float(send_amount))

                transaction = btc_rpc_call.do_get_transaction(send_response_tx_id)
                log.info(abs(transaction["fee"]))
                send_response = SendFromResponse(tx_id=send_response_tx_id, status="OK",
                                                 fee=abs(transaction["fee"]), test=is_test_net)
                send_response_serializer = SendFromResponseSerializer(send_response)
            except JSONRPCException as ex:
                log.info("Error: %s" % ex.error['message'])
                send_response = SendFromResponse(status="NOK", message=ex.error['message'], test=is_test_net)
                send_response_serializer = SendFromResponseSerializer(send_response)

            return Response(data=send_response_serializer.data, status=status.HTTP_200_OK)
  def __get_txIds(self, account="", btc_service=BTCRPCCall()):

    if not isinstance(btc_service, BTCRPCCall):
      raise TypeError("Expected object BTCRPCCall, got %s" % (type(btc_service),))

    transactions = btc_service.list_transactions(account=account, count=88)
    transactions_with_tx_id = []

    for transaction in transactions:
      if 'txid' in transaction and transaction['category'] == 'receive':
        transaction_with_tx_id = check_multi_receives.TxIdTransaction(txid=transaction['txid'],
                                                                      received=transaction['amount'],
                                                                      confirmations=transaction['confirmations'],
                                                                      date=datetime.fromtimestamp(transaction['time']))
        transactions_with_tx_id.append(transaction_with_tx_id.__dict__)

    # txIds = map(lambda transaction: transaction['txid'], transactions_with_tx_id)
    return transactions_with_tx_id
  def __receive_amount_for_risk(self, wallet_address="", tx_ids=[], btc_service=BTCRPCCall()):

    if not isinstance(btc_service, BTCRPCCall):
      raise TypeError("Expected object BTCRPCCall, got %s" % (type(btc_service),))

    result = Decimal(
      btc_service.amount_received_by_address(address=wallet_address, confirms=RISK_HIGH_CONFIRMATIONS))

    low_risk_counter = 0
    medium_risk_counter = 0
    high_risk_counter = 0

    for tx_id in tx_ids:
      log.info("tx_id confirmation is %d.", tx_id["confirmations"])
      if tx_id["confirmations"] == RISK_HIGH_CONFIRMATIONS:
        high_risk_counter += 1
      if tx_id["confirmations"] >= RISK_MEDIUM_CONFIRMATIONS and tx_id["confirmations"] < RISK_LOW_CONFIRMATIONS:
        medium_risk_counter += 1
      if tx_id["confirmations"] >= RISK_LOW_CONFIRMATIONS:
        low_risk_counter += 1

    log.info("low_risk_counter: %d, medium_risk_counter: %d, high_risk_counter: %d",
             low_risk_counter, medium_risk_counter, high_risk_counter)

    if high_risk_counter >= 1:
      log.info("received with 0 confirmed")
      log.info(result)
      log.info("high")
      return {"result": result, "risk": 'high'}

    if medium_risk_counter >= 1:
      log.info("received with 1 confirmed")
      log.info(result)
      log.info("medium")
      return {"result": result, "risk": 'medium'}

    if low_risk_counter >= 1:
      log.info("received with 6 confirmed")
      log.info(result)
      log.info("low")
      return {"result": result, "risk": 'low'}
  def post(self, request):
    log.info(request.data)
    post_serializers = check_multi_receives.PostParametersSerializer(data=request.data)

    response_list = []
    if post_serializers.is_valid():
      log.info(post_serializers.data["transactions"])
      transactions = post_serializers.data["transactions"]
      try:
        btc_rpc_call = BTCRPCCall()
        is_test_net = constantutil.check_service_is_test_net(btc_rpc_call)
        for transaction in transactions:
          log.info(transaction)

          transaction_address = transaction["address"]

          address_validation = btc_rpc_call.do_validate_address(address=transaction_address)

          if address_validation["isvalid"] is False:
            return Response(transaction_address + " is not a valid address",
                            status=status.HTTP_400_BAD_REQUEST)

          if address_validation["ismine"] is False:
            log.info(transaction_address + " is not an address of the wallet")
            return Response(transaction_address + " is not an address of the wallet",
                            status=status.HTTP_400_BAD_REQUEST)

          tx_ids = self.__get_txIds(transaction["address"], btc_service=btc_rpc_call)
          log.debug(tx_ids)

          received_with_risk = self.__receive_amount_for_risk(wallet_address=transaction_address,
                                                              tx_ids=tx_ids,
                                                              btc_service=btc_rpc_call)

          received = Decimal(received_with_risk["result"]) if received_with_risk else 0.0
          risk = received_with_risk["risk"] if received_with_risk else "low"
          log.info("received: %f, risk: %s", received, risk)


          response = check_multi_receives.ReceiveInformationResponse(currency=transaction["currency"],
                                                                     address=transaction_address,
                                                                     received=received,
                                                                     risk=risk,
                                                                     txs=tx_ids)
          print(address_validation)
          response_list.append(response.__dict__)
          receives_response = check_multi_receives.ReceivesInformationResponse(receives=response_list,
                                                                               test=is_test_net)
      except JSONRPCException as ex:
          log.error("Error: %s" % ex.error['message'])
          error_message = "Bitcoin RPC error, check if username and password for node is correct. Message from " \
                          "python-bitcoinrpc: " + ex.message
          receives_response = check_multi_receives.ReceivesInformationResponse(receives=response_list,
                                                                               test=True,
                                                                               error=1,
                                                                               error_message=error_message
                                                                               )
      except socket_error as serr:
        if serr.errno != errno.ECONNREFUSED:
          receives_response = check_multi_receives.ReceivesInformationResponse(receives=[],
                                                                               test=True,
                                                                               error=1,
                                                                               error_message="A general socket error was raised."
                                                                               )
        else:
          receives_response = check_multi_receives.ReceivesInformationResponse(receives=[],
                                                                               test=True,
                                                                               error=1,
                                                                               error_message="Connection refused error, "
                                                                                             "check if the wallet node is down."
                                                                               )

      response_dict = receives_response.__dict__

      response_serializer = check_multi_receives.ReceivesInformationResponseSerializer(data=response_dict)

      if response_serializer.is_valid():
        return Response(response_serializer.data, status=status.HTTP_201_CREATED)
      else:
        return Response(response_serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)

    return Response(post_serializers.errors, status=status.HTTP_400_BAD_REQUEST)
    def post(self, request):
        global response_serializer
        post_serializer = transfers_using_sendtoaddress.PostParametersSerializer(
            data=request.data)

        yml_config = ConfigFileReader()

        if post_serializer.is_valid():
            transfer_list = post_serializer.data["transfers"]
            response_list = []
            try:
                btc_rpc_call = BTCRPCCall()
                is_test_net = constantutil.check_service_is_test_net(
                    btc_rpc_call)

                for transfer in transfer_list:
                    log.info(transfer)

                    currency = transfer["currency"]
                    txFee = transfer["txFee"]
                    send_amount = transfer["amount"]
                    log.info(send_amount)
                    to_address = yml_config.get_safe_address_to_be_transferred(
                        currency=currency)

                    log.info("%s, %s, %s" %
                             (currency, to_address, send_amount))

                    to_address_is_valid = (btc_rpc_call.do_validate_address(
                        address=to_address))["isvalid"]

                    log.info("%s" % (to_address_is_valid))
                    if to_address_is_valid:
                        try:
                            if lock.locked() is False:
                                lock.acquire()
                                btc_rpc_call.set_tx_fee(txFee)
                                send_response_tx_id = btc_rpc_call.send_to_address(
                                    address=to_address, amount=send_amount)
                                lock.release()

                                transaction = btc_rpc_call.do_get_transaction(
                                    send_response_tx_id)

                                response = \
                                    transfers_using_sendtoaddress.TransferInformationResponse(currency=currency,
                                                                                              to_address=to_address,
                                                                                              amount=Decimal(str(send_amount)),
                                                                                              fee=abs(transaction["fee"]),
                                                                                              message="Transfer is done",
                                                                                              status="ok",
                                                                                              txid=send_response_tx_id)

                        except JSONRPCException as ex:
                            if lock.locked() is True:
                                lock.release()
                            log.error("Error: %s" % ex.error['message'])
                            response = transfers_using_sendtoaddress.TransferInformationResponse(
                                currency=currency,
                                to_address=to_address,
                                amount=Decimal(str(send_amount)),
                                message=ex.error['message'],
                                status="fail",
                                txid="")
                        except (LockTimeoutException, LockException):
                            log.error("Error: %s" %
                                      "LockTimeoutException or LockException")
                            response = transfers_using_sendtoaddress.TransferInformationResponse(
                                currency=currency,
                                to_address=to_address,
                                amount=Decimal(str(send_amount)),
                                message="LockTimeoutException or LockException",
                                status="fail",
                                txid="")
                        except (ConnectionError, ServerDown):
                            log.error(
                                "Error: ConnectionError or ServerDown exception"
                            )
                            response = transfers_using_sendtoaddress.TransferInformationResponse(
                                currency=currency,
                                to_address=to_address,
                                amount=Decimal(str(send_amount)),
                                message=
                                "Error: ConnectionError or ServerDown exception",
                                status="fail",
                                txid="")

                        response_list.append(response.__dict__)

                    else:
                        log.info("do nothing")
                        response = transfers_using_sendtoaddress.TransferInformationResponse(
                            currency=currency,
                            to_address=to_address,
                            amount=Decimal(str(send_amount)),
                            message="to_address is not valid",
                            status="fail",
                            txid="")
                        response_list.append(response.__dict__)

                log.info(response_list)

                transfers_response = transfers_using_sendtoaddress.TransfersInformationResponse(
                    transfers=response_list, test=is_test_net)
            except JSONRPCException as ex:
                if lock.locked() is True:
                    lock.release()
                log.error("Error: %s" % ex.error['message'])
                transfers_response = transfers_using_sendtoaddress.TransfersInformationResponse(
                    transfers=[],
                    test=True,
                    error=1,
                    error_message=
                    "Bitcoin RPC error, check if username and password "
                    "for node is correct. Message from python-bitcoinrpc: " +
                    ex.message)
            except socket_error as serr:
                if lock.locked() is True:
                    lock.release()
                if serr.errno != errno.ECONNREFUSED:
                    transfers_response = transfers_using_sendtoaddress.TransfersInformationResponse(
                        transfers=[],
                        test=True,
                        error=1,
                        error_message="A general socket error was raised.")
                else:
                    transfers_response = transfers_using_sendtoaddress.TransfersInformationResponse(
                        transfers=[],
                        test=True,
                        error=1,
                        error_message=
                        "Connection refused error, check if the wallet"
                        " node is down.")
            response_dict = transfers_response.__dict__

            response_serializer = transfers_using_sendtoaddress.TransfersInformationResponseSerializer(
                data=response_dict)

            if response_serializer.is_valid():
                return Response(response_serializer.data,
                                status=status.HTTP_200_OK)
            else:
                return Response(response_serializer.errors,
                                status=status.HTTP_406_NOT_ACCEPTABLE)

        return Response(post_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Example #11
0
class BTCCurrencyTransfer(AbstractDigitalCurrencyTransfer):
    def __init__(self):

        self.yml_config = ConfigFileReader()
        self.fee = self.yml_config.get_reserved_fee_for_transferring(
            currency='btc')
        self.confirms = self.yml_config.get_min_transfer_confirmations(
            currency='btc')
        self.btc_rpc_call = BTCRPCCall(wallet='receive', currency='btc')
        self.coin_to_be_send_dict = self.__init_dict_of_accounts()

    def __get_total_amount_in_wallet(self):

        if self.coin_to_be_send_dict.values():
            return reduce(lambda (coin_value), y: coin_value + y,
                          self.coin_to_be_send_dict.values())
        else:
            return 0

    def __init_dict_of_accounts(self):

        lists_received_by_account = self.btc_rpc_call.list_accounts(
            self.confirms)

        dict_coin_to_be_send = {}

        for received_account, amount in lists_received_by_account.iteritems():

            amount_balance = self.btc_rpc_call.get_balance(
                received_account, self.confirms)

            if amount_balance > 0:
                dict_coin_to_be_send[received_account] = amount_balance

            if amount_balance < 0:
                logger_file.error("Minus value is in the account %s ",
                                  received_account)
                raise SystemExit("Minus value is in an account!!")

        return dict_coin_to_be_send

    def __create_an_address_with_account_assigned(self):

        new_address = self.btc_rpc_call.do_get_new_address()
        self.btc_rpc_call.do_set_account(new_address, new_address)
        return new_address

    def main(self):

        min_transfer = self.yml_config.get_min_transfer_amount(currency='btc')

        total_amount = self.__get_total_amount_in_wallet()
        balance_amount = (self.btc_rpc_call.do_getinfo())['balance']

        amount_thresh = abs(balance_amount - total_amount)

        if amount_thresh > 0.0001:
            logger_file.error(
                "%d confirmed amount %s  != the total receiving balance %s, need more confirms",
                int(self.confirms), total_amount, balance_amount)

        logger_file.info("Total amount of coins to be transfer: %f" %
                         total_amount)

        if total_amount >= min_transfer:
            logger_file.info("Init transferring...")
            logger_file.info(
                "Creating a temporary address for moving coins...")
            btc_account = self.__create_an_address_with_account_assigned()
            logger_file.info("Starting to move coins to %s", btc_account)

            for received_account, amount in self.coin_to_be_send_dict.iteritems(
            ):
                """
                logger_file.info("%s, %s, %f", received_account,
                                 self.btc_rpc_call.get_addresses_by_account(received_account), amount)
                """
                if self.btc_rpc_call.move(received_account, btc_account,
                                          float(amount)):
                    pass
                else:
                    logger_file.error("Fail to move coins to from %s to %s!",
                                      received_account, btc_account)

            send_to_address = self.yml_config.get_safe_address_to_be_transferred(
                currency='btc')

            amount_to_transfer = float(total_amount) - float(self.fee)

            logger_file.info(
                "Starting transferring %f coins to address: %s from account: %s",
                amount_to_transfer, send_to_address, btc_account)

            self.btc_rpc_call.send_from(btc_account, send_to_address,
                                        amount_to_transfer)
            logger_file.info("Transfer is done")
        else:
            logger_file.info("It is not ready to do the coin transferring!")

    def main_test(self):

        total_amount = self.__get_total_amount_in_wallet()
        logger_file.info(total_amount)

        balance_amount = (self.btc_rpc_call.do_getinfo())['balance']
        logger_file.info(balance_amount)

        logger_file.info(len(self.coin_to_be_send_dict))

        for received_account, amount in self.coin_to_be_send_dict.iteritems():
            logger_file.info("account: %s, amount: %f", received_account,
                             amount)
Example #12
0
class BTCCurrencyTransfer(AbstractDigitalCurrencyTransfer):

    def __init__(self):

        self.yml_config = ConfigFileReader()
        self.fee = self.yml_config.get_reserved_fee_for_transferring(currency='btc')
        self.confirms = self.yml_config.get_min_transfer_confirmations(currency='btc')
        self.btc_rpc_call = BTCRPCCall(wallet='receive', currency='btc')
        self.coin_to_be_send_dict = self.__init_dict_of_accounts()

    def __get_total_amount_in_wallet(self):

        if self.coin_to_be_send_dict.values():
            return reduce(lambda (coin_value), y: coin_value + y, self.coin_to_be_send_dict.values())
        else:
            return 0

    def __init_dict_of_accounts(self):

        lists_received_by_account = self.btc_rpc_call.list_accounts(self.confirms)

        dict_coin_to_be_send = {}

        for received_account, amount in lists_received_by_account.iteritems():

            amount_balance = self.btc_rpc_call.get_balance(received_account, self.confirms)

            if amount_balance > 0:
                dict_coin_to_be_send[received_account] = amount_balance

            if amount_balance < 0:
                logger_file.error("Minus value is in the account %s ", received_account)
                raise SystemExit("Minus value is in an account!!")

        return dict_coin_to_be_send

    def __create_an_address_with_account_assigned(self):

        new_address = self.btc_rpc_call.do_get_new_address()
        self.btc_rpc_call.do_set_account(new_address, new_address)
        return new_address

    def main(self):

        min_transfer = self.yml_config.get_min_transfer_amount(currency='btc')

        total_amount = self.__get_total_amount_in_wallet()
        balance_amount = (self.btc_rpc_call.do_getinfo())['balance']

        amount_thresh = abs(balance_amount - total_amount)

        if amount_thresh > 0.0001:
            logger_file.error("%d confirmed amount %s  != the total receiving balance %s, need more confirms",
                              int(self.confirms), total_amount, balance_amount)

        logger_file.info("Total amount of coins to be transfer: %f" % total_amount)

        if total_amount >= min_transfer:
            logger_file.info("Init transferring...")
            logger_file.info("Creating a temporary address for moving coins...")
            btc_account = self.__create_an_address_with_account_assigned()
            logger_file.info("Starting to move coins to %s", btc_account)

            for received_account, amount in self.coin_to_be_send_dict.iteritems():
                """
                logger_file.info("%s, %s, %f", received_account,
                                 self.btc_rpc_call.get_addresses_by_account(received_account), amount)
                """
                if self.btc_rpc_call.move(received_account, btc_account, float(amount)):
                    pass
                else:
                    logger_file.error("Fail to move coins to from %s to %s!", received_account, btc_account)

            send_to_address = self.yml_config.get_safe_address_to_be_transferred(currency='btc')

            amount_to_transfer = float(total_amount) - float(self.fee)

            logger_file.info("Starting transferring %f coins to address: %s from account: %s", amount_to_transfer,
                             send_to_address, btc_account)

            self.btc_rpc_call.send_from(btc_account, send_to_address, amount_to_transfer)
            logger_file.info("Transfer is done")
        else:
            logger_file.info("It is not ready to do the coin transferring!")

    def main_test(self):

        total_amount = self.__get_total_amount_in_wallet()
        logger_file.info(total_amount)

        balance_amount = (self.btc_rpc_call.do_getinfo())['balance']
        logger_file.info(balance_amount)

        logger_file.info(len(self.coin_to_be_send_dict))

        for received_account, amount in self.coin_to_be_send_dict.iteritems():
            logger_file.info("account: %s, amount: %f", received_account, amount)
Example #13
0
    def post(self, request):
        post_serializer = transfers.PostParametersSerializer(data=request.DATA)

        # from_account_balance = btc_rpc_call.get_balance(account=serializer)

        yml_config = ConfigFileReader()


        if post_serializer.is_valid():

            btc_rpc_call = BTCRPCCall()
            is_test_net = constantutil.check_service_is_test_net(btc_rpc_call)

            transfer_list = post_serializer.data["transfers"]
            log.info(is_test_net)
            response_list = []


            for transfer in transfer_list:
                log.info(transfer)
                currency = transfer["currency"]
                from_address = transfer["from_address"]

                send_amount = transfer["amount"]
                log.info(send_amount)

                to_address = yml_config.get_safe_address_to_be_transferred(currency=currency)

                log.info("%s, %s, %s, %s" % (currency, from_address,  to_address, send_amount))
                #log.info("%s %s" % currency, from_address)

                from_address_is_valid = (btc_rpc_call.do_validate_address(address=from_address))["isvalid"]
                to_address_is_valid = (btc_rpc_call.do_validate_address(address=to_address))["isvalid"]

                log.info("%s, %s" % (from_address_is_valid, to_address_is_valid))

                if from_address_is_valid and to_address_is_valid:
                    try:

                        send_response_tx_id = btc_rpc_call.send_from(from_account=from_address,
                                                                     to_address=to_address, amount=send_amount)

                        response = transfers.TransferInformationResponse(currency=currency,
                                                                         from_address=from_address,
                                                                         to_address=to_address,
                                                                         amount=Decimal(str(send_amount)),
                                                                         status="ok",
                                                                         txid=send_response_tx_id)

                        response_list.append(response.__dict__)
                    except JSONRPCException as ex:
                        log.info("Error: %s" % ex.error['message'])
                        response = transfers.TransferInformationResponse(currency=currency,
                                                                         from_address=from_address,
                                                                         to_address=to_address,
                                                                         amount=Decimal(str(send_amount)),
                                                                         status="fail",
                                                                         txid="")
                        response_list.append(response.__dict__)

                else:
                    log.info("do nothing")
                    response = transfers.TransferInformationResponse(currency=currency,
                                                                     from_address=from_address,
                                                                     to_address=to_address,
                                                                     amount=Decimal(str(send_amount)),
                                                                     status="fail",
                                                                     txid="")
                    response_list.append(response.__dict__)

            log.info(response_list)

            transfers_response = transfers.TransfersInformationResponse(transfers=response_list, test=is_test_net)

            response_dict = transfers_response.__dict__

        response_serializer = transfers.TransfersInformationResponseSerializer(data=response_dict)

        if response_serializer.is_valid():
            return Response(response_serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(response_serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)

        return Response(post_serializers.errors, status=status.HTTP_400_BAD_REQUEST)
    def post(self, request):
        serializer_post = send_many_vo.SendManyPostParametersSerializer(
            data=request.data)

        if serializer_post.is_valid():
            log.info(serializer_post.data)
            currency = serializer_post.data["currency"]
            wallet = serializer_post.data["wallet"]
            txFee = serializer_post.data["txFee"]
            btc_rpc_call = BTCRPCCall(wallet=wallet, currency=currency)

            from_account = serializer_post.data['fromAddress']
            log.info(from_account)
            amounts = serializer_post.data['toSend']
            amounts_dict = dict()

            for amount in amounts:
                if amount['toAddress'] in amounts_dict:
                    #As the values in amounts_dict[amount['toAddress']] and amount['amount'] is a string, They need to be converted
                    current_amount = float(amounts_dict[amount['toAddress']])
                    extra_amount = float(amount['amount'])
                    new_amount = current_amount + extra_amount
                    amounts_dict[amount['toAddress']] = '%.9f' % new_amount
                else:
                    amounts_dict[amount['toAddress']] = amount['amount']

            response = None

            try:

                is_test_net = constantutil.check_service_is_test_net(
                    btc_rpc_call)

                if lock.locked() is False:
                    lock.acquire()
                    btc_rpc_call.set_tx_fee(txFee)
                    isSuccess, result = btc_rpc_call.send_many(
                        from_account=from_account, amounts=amounts_dict)
                    lock.release()

                    if (isSuccess):
                        log.info(result)
                        transaction = btc_rpc_call.do_get_transaction(result)
                        if transaction is None:
                            response = send_many_vo.SendManyResponse(
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                fee=0,
                                message="BTC server - " + wallet + "is done.",
                                test=is_test_net,
                                error=1)

                        else:
                            response = send_many_vo.SendManyResponse(
                                tx_id=result,
                                status=status.HTTP_200_OK,
                                fee=abs(transaction["fee"]),
                                message="Send many is done.",
                                test=is_test_net)

                    elif result is not None and isinstance(
                            result, JSONRPCException):

                        if lock.locked() is True:
                            lock.release()
                        log.info("Error: %s" % result.error['message'])
                        response = send_many_vo.SendManyResponse(
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            fee=0,
                            message=result.error['message'],
                            test=is_test_net,
                            error=1)
                    elif result is not None and isinstance(
                            result, socket.error):
                        log.info(result.errno == errno.ECONNREFUSED)
                        log.info(result.message)
                        response = send_many_vo.SendManyResponse(
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            fee=0,
                            message=result.message,
                            test=is_test_net,
                            error=1)

            except (LockTimeoutException, LockException):
                is_test_net = constantutil.check_service_is_test_net(
                    btc_rpc_call)
                log.error("Error: %s" %
                          "LockTimeoutException or LockException")
                response = send_many_vo.SendManyResponse(
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    fee=0,
                    message="LockTimeoutException or LockException",
                    test=is_test_net,
                    error=1)
            except (ConnectionError, ServerDown):
                log.error("Error: ConnectionError or ServerDown exception")
                response = send_many_vo.SendManyResponse(
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    fee=0,
                    message="Error: ConnectionError or ServerDown exception",
                    test=True,
                    error=1)

            except JSONRPCException as ex:
                if lock.locked() is True:
                    lock.release()
                log.error("Error: %s" % ex.error['message'])
                error_message = "Bitcoin RPC error, check if username and password for node is correct. Message from " \
                                "python-bitcoinrpc: " + ex.message
                response = send_many_vo.SendManyResponse(
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    fee=0,
                    message=error_message,
                    test=True,
                    error=1,
                    error_message=error_message)
            except socket_error as serr:
                if lock.locked() is True:
                    lock.release()
                if serr.errno != errno.ECONNREFUSED:
                    error_message = "A general socket error was raised."
                    response = send_many_vo.SendManyResponse(
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        fee=0,
                        message=error_message,
                        test=True,
                        error=1,
                        error_message=error_message)
                else:
                    error_message = "Connection refused error, check if the wallet node is down."
                    response = send_many_vo.SendManyResponse(
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        fee=0,
                        message=error_message,
                        test=True,
                        error=1,
                        error_message=error_message)

            if (response is not None):
                send_many_response_serializer = send_many_vo.SendManyResponseSerializer(
                    data=response.__dict__)
            else:
                is_test_net = constantutil.check_service_is_test_net(
                    btc_rpc_call)
                response = send_many_vo.SendManyResponse(
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    fee=0,
                    message="Error: response is None",
                    test=is_test_net,
                    error=1)
                send_many_response_serializer = send_many_vo.SendManyResponseSerializer(
                    data=response.__dict__)

            if send_many_response_serializer.is_valid():
                return Response(send_many_response_serializer.data,
                                status=status.HTTP_200_OK)
            else:
                return Response(send_many_response_serializer.errors,
                                status=status.HTTP_406_NOT_ACCEPTABLE)

        return Response(serializer_post.errors,
                        status=status.HTTP_400_BAD_REQUEST)
    def post(self, request):
        post_serializers = wallet_balance.GetWalletBalancePostParameterSerializer(
            data=request.data)

        wallet_balance_response_list = []
        if post_serializers.is_valid():
            currency = post_serializers.data["currency"]
            wallet_list = yml_config.get_wallet_list(currency)
            log.info(wallet_list)
            for wallet in wallet_list:
                try:
                    log.info(wallet)
                    btc_rpc_call = BTCRPCCall(wallet=wallet, currency=currency)
                    is_test_net = constantutil.check_service_is_test_net(
                        btc_rpc_call)
                    log.info(is_test_net)
                    balance = btc_rpc_call.get_wallet_balance()
                    log.info(format(balance, '0.8f'))
                    wallet_balance_response = wallet_balance.WalletBalanceResponse(
                        wallet=wallet,
                        balance=Decimal(balance),
                        test=is_test_net)

                    log.info(wallet_balance_response.__dict__)
                    wallet_balance_response_list.append(
                        wallet_balance_response.__dict__)
                except socket_error as serr:
                    if serr.errno != errno.ECONNREFUSED:
                        wallet_balance_response = wallet_balance.WalletBalanceResponse(
                            wallet=wallet,
                            balance=Decimal(0),
                            test=True,
                            error=1,
                            error_message="A general socket error was raised.")
                        wallet_balance_response_list.append(
                            wallet_balance_response.__dict__)
                    else:
                        wallet_balance_response = wallet_balance.WalletBalanceResponse(
                            wallet=wallet,
                            balance=Decimal(0),
                            test=True,
                            error=1,
                            error_message=
                            "Connection refused error, check if the wallet node is down."
                        )
                        wallet_balance_response_list.append(
                            wallet_balance_response.__dict__)
                except JSONRPCException as ex:
                    wallet_balance_response = wallet_balance.WalletBalanceResponse(
                        wallet=wallet,
                        balance=Decimal(0),
                        test=True,
                        error=1,
                        error_message=
                        "Bitcoin RPC error, check if username and password for node is correct. Message from python-bitcoinrpc: "
                        + ex.message)
                    wallet_balance_response_list.append(
                        wallet_balance_response.__dict__)

            wallets_balance_response = wallet_balance.WalletsBalanceResponse(
                wallets=wallet_balance_response_list)

            wallets_balance_response_serializer = \
                wallet_balance.WalletsBalanceResponseSerializer(data=wallets_balance_response.__dict__)

            if wallets_balance_response_serializer.is_valid():
                return Response(wallets_balance_response_serializer.data,
                                status=status.HTTP_201_CREATED)
            else:
                return Response(wallets_balance_response_serializer.errors,
                                status=status.HTTP_406_NOT_ACCEPTABLE)

        return Response(post_serializers.errors,
                        status=status.HTTP_400_BAD_REQUEST)