Ejemplo n.º 1
0
    def get(self, request):

        print('Started ' + self.__class__.__name__ + ' get method')
        try:
            network = request.GET.get('network')
            wallet_id = request.GET.get('wallet_id')
            withsum = request.GET.get('withsum')
            withsum = bool(withsum)
            print('Started ', self.__class__.__name__, '  wallet_id=%s, withsum=%s, network=%s ' % (str(wallet_id),
                                                                                             bool(str(withsum)),network))
            address_list = []
            if  wallet_id and network :
                wallet = HDWallet(wallet_id, db_uri=db_uri)
                wallet_address_list = wallet.addresslist()
                print('Wallet=%s, with unspent value=%s' %(wallet_id,str(wallet.balance())))

                address_list = '|'.join([str(a) for a in wallet_address_list])
                block_service_url = get_env_var(
                    'blockchain.service.url') + '/multiaddr?active=' + address_list
                print('service_url for get balance', block_service_url)
                resp = requests.get(block_service_url)
                print('\nreceived for blcokchain multiaddr resp', resp.status_code)
                address_list = json.loads(resp.text)
                address_list =  self.getunspent(wallet_address_list,address_list,withsum)
                return JsonResponse(address_list, safe=False)
            else:
                raise ValidationError(get_env_var('exception.validation.unspent.no_wallet_or_no_network'))
        except ServiceException as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(e)
        except Exception as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(get_env_var('exception.business.unspent.serviceexception'))
Ejemplo n.º 2
0
    def post(self, request):
        print("enter sign and send")
        try:
            data = JSONParser().parse(request)
            username = data.get("username")
            hex = data.get("hex")
            coin_type = data.get("type")
            if username and coin_type and hex:
                print(username + "username")
                service_url = get_env_var(
                    'service.url'
                ) + '/address/?action=receive&username='******'&type=' + coin_type
                print(service_url + "service_url")
                resp = requests.get(service_url, auth=service_auth)
                if resp.status_code != 200:
                    print('address response', resp.text)
                    raise ServiceException(
                        get_env_var(
                            'exception.business.sign.serviceexception'))
                else:
                    print('address response', resp.text)
                    response_list = json.loads(resp.text)
                    signsend = SignSendView()
                    sign_dict_str = signsend.sign_txn(hex, response_list)
                    print('sign request ' + sign_dict_str)
                    url = get_url(coin_type, "signtxn")
                    # url = 'https://66f49c90-24e2-4d2b-891d-5746233c8ae7.mock.pstmn.io/sign'

                    if coin_type == 'BTC':
                        resp = requests.post(url,
                                             auth=btc_auth,
                                             data=sign_dict_str)
                    elif coin_type == 'LTC':
                        resp = requests.post(url,
                                             auth=ltc_auth,
                                             data=sign_dict_str)
                    print(resp.status_code)
                    if resp.status_code != 200:
                        print('sign response ' + resp.text)
                        raise ServiceException(
                            get_env_var(
                                'exception.business.sign.serviceexception'))
                    else:
                        print('sign response ' + resp.text)
                        response_dict = json.loads(resp.text)
                        return JsonResponse(response_dict, safe=False)

            else:
                raise ValidationError(
                    get_env_var(
                        'exception.validation.sign.no_user_or_no_coin_type_or_no_hex'
                    ))
        except Exception as e:
            track = traceback.format_exc()
            print(track)
            print("error" + str(resp.status_code))
            raise e
Ejemplo n.º 3
0
    def post(self,request):

        print('Started ' + self.__class__.__name__ + ' get method')
        try:
            data = JSONParser().parse(request)
            network = data.get('network')
            hex = data.get('hex')

            txn_data = {}
            txn_data['wallet_id'] = data.get('wallet_id')
            txn_data['type'] = data.get('txn_type')
            txn_data['destination'] = data.get('address_id')
            txn_data['destination_amount'] = data.get('amount')
            txn_data['message'] = data.get('message')
            txn_data['includes_fee'] = data.get('includes_fee')

            print(' txn with data' + str(data))

            if network and hex:

                if network == 'bitcoin':
                    txn_data['network'] = 'btc'
                    resp = btc_srv.sendrawtransaction(hex)
                    txn_data['network'] = 'ltc'
                elif network == 'litecoin':
                    resp = ltc_srv.sendrawtransaction(hex)
                print('\nreceived for sendrawtransaction  resp', resp.status_code, 'response %s' %(resp.text))
                
                if resp.status_code != 200:
                    Util.sendMessage(message=hex,destination='/queue/txn.failure')
                    raise ServiceException(get_env_var('exception.business.send.serviceexception'))
                else:

                    if resp.text:
                        print('saving in txn')
                        response_dict = json.loads(resp.text)
                        txn_data['txn_id'] = response_dict['result']
                        print('saving in txn with data' + str(txn_data))
                        Util.sendMessage(message=txn_data, destination='/queue/txn')
                        serializer = TxnSerializer(data=txn_data)
                        if serializer.is_valid():
                            serializer.save()
                        else:
                            return JsonResponse(serializer.errors, status=400)
                        return JsonResponse(serializer.data, status=201, safe=False)
                    else:
                        raise ServiceException(get_env_var('exception.business.send.serviceexception'))
            else:
                raise ValidationError(get_env_var('exception.validation.send.no_network_or_no_hex'))

        except Exception as e:
            track = traceback.format_exc()
            logger.exception(track)
            print("error" + str(track))
            raise e;
Ejemplo n.º 4
0
    def getunspent(self,wallet_address_list,list,withsum):

        try:
            if len(list) > 0:
                address_list = list['txs']
                #flatten the list
                flattent_address_list = []
                for wl in wallet_address_list:
                    for adr_list in address_list:
                        for in_txn in adr_list.get('inputs'):
                            if (in_txn.get('prev_out').get('addr') == wl):
                                for out in adr_list.get('out'):
                                    add_row = {}
                                    add_row['txid'] = adr_list.get('hash')
                                    add_row['vout'] = out.get('n')
                                    add_row['address'] = out.get('addr')
                                    flattent_address_list.append(add_row)
                if withsum:
                    flattent_address_list.append({"toal_unspent": list.get('wallet').get('final_balance')})

                return flattent_address_list

        except Exception as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(e)
Ejemplo n.º 5
0
	def getNewAddress(account_id,wallet_id):
		try:
			wallet = HDWallet(wallet_id, db_uri=db_uri)
			address = wallet.new_key(account_id=account_id)
			address = Address(address_id=address.address, network_name=address.network_name)
			return address

		except Exception as e:
			raise ServiceException(get_env_var('exception.business.newaddress.dumpkey.serviceexception'))
Ejemplo n.º 6
0
    def getBitcoinTxn(self, list):

        try:
            txn_list = []
            if len(list) > 0:
                address_list = list.get('txs')
                #flatten the list
                print('\naddress_list ', address_list)
                for adr_list in address_list:
                    for in_txn in adr_list.get('inputs'):
                        print(' in_txn ', in_txn)
                        print(' in_txn spent  ',
                              in_txn.get('prev_out').get('spent'))
                        if bool(in_txn.get('prev_out').get('spent')) == True:
                            print(' in true')
                            add_row = {}
                            add_row['txid'] = adr_list.get('hash')
                            add_row['value'] = in_txn.get('prev_out').get(
                                'value')
                            add_row['address'] = in_txn.get('prev_out').get(
                                'addr')
                            add_row['action'] = 'send'
                            add_row['time'] = datetime.fromtimestamp(
                                adr_list.get('time'))
                            txn_list.append(add_row)
                        else:
                            add_row = {}
                            add_row['txid'] = adr_list.get('hash')
                            add_row['value'] = in_txn.get('prev_out').get(
                                'value')
                            add_row['address'] = in_txn.get('prev_out').get(
                                'addr')
                            add_row['action'] = 'receive'
                            add_row['time'] = datetime.fromtimestamp(
                                adr_list.get('time'))
                            txn_list.append(add_row)

                    for out in adr_list.get('out'):
                        add_row = {}
                        add_row['txid'] = adr_list.get('hash')
                        add_row['value'] = out.get('value')
                        add_row['address'] = out.get('addr')
                        add_row['action'] = 'receive'
                        add_row['time'] = datetime.fromtimestamp(
                            adr_list.get('time'))
                        txn_list.append(add_row)

            return txn_list

        except Exception as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(e)
Ejemplo n.º 7
0
    def getLitecoinTxn(self, list):

        try:
            txn_list = []

            for list in list:

                if len(list) > 0:
                    address_list = list.get('txs')
                    #flatten the list
                    print('\naddress_list ', address_list)
                    for adr_list in address_list if address_list else []:
                        for in_txn in adr_list.get('inputs'):

                            print(' in_txn ', in_txn)
                            print(' in_txn addresses  ',
                                  in_txn.get('addresses'))
                            for address in in_txn.get(
                                    'addresses') if in_txn.get(
                                        'addresses') else []:
                                print(' in true')
                                add_row = {}
                                add_row['txid'] = adr_list.get('hash')
                                add_row['value'] = in_txn.get('output_value')
                                add_row['address'] = address
                                add_row['action'] = 'send'
                                add_row['time'] = adr_list.get('received')
                                txn_list.append(add_row)

                        for out in adr_list.get('outputs'):
                            add_row = {}
                            add_row['txid'] = adr_list.get('hash')
                            add_row['value'] = out.get('value')
                            add_row['address'] = out.get(
                                'addresses')[0] if out.get('addresses') else ''
                            add_row['action'] = 'receive'
                            add_row['time'] = adr_list.get('received')
                            txn_list.append(add_row)

            return txn_list

        except Exception as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(e)
Ejemplo n.º 8
0
    def post(self, request, *args, **kwargs):

        print('Started ' + self.__class__.__name__ + ' post method %s' %
              (request.data))
        try:

            serializer = self.serializer_class(data=request.data,
                                               context={'request': request})

            if serializer.is_valid():
                user = serializer.validated_data['user']
                print('Started ' + self.__class__.__name__ + ' post user='******'exception.business.auth.serviceexception'))
                else:
                    token, created = Token.objects.get_or_create(user=user)
                    is_expired, token = token_expire_handler(token)

                return Response({
                    'username': user.username,
                    'user_id': user.user_id,
                    'token': token.key
                })
            else:
                response_dict = {
                    'status': 'error',
                    # the format of error message determined by you base exception class
                    'msg': serializer.errors
                }
                return JsonResponse(response_dict, status=400)

        except Exception as e:
            raise e
Ejemplo n.º 9
0
    def post(self, request):
        print('Started ' + self.__class__.__name__ + ' get method')
        try:

            data = JSONParser().parse(request)
            network = data.get('network')
            output_address = data.get('address_id')
            wallet_id = data.get('wallet_id')
            send_amount = int(data.get('amount'))

            print(
                'Started ', self.__class__.__name__,
                '  wallet_id=%s, withsum=%s, network=%s ' %
                (str(wallet_id), (str(output_address)), network))

            wallet = HDWallet(wallet_id, db_uri=db_uri)
            change_address = wallet.get_key_change()
            change_address = change_address.address
            print('change_address ', change_address)

            if wallet_id:
                service_url = get_env_var(
                    'service.url') + '/unspent/?wallet_id=' + str(
                        wallet_id) + '&network=' + network
                print('service_url for  unspent', service_url)
                resp = requests.get(service_url, auth=service_auth)
                print('received status code for unspent resp',
                      resp.status_code, ' and response %s' % (resp.text))
                if resp.status_code != 200:
                    raise ServiceException(
                        get_env_var('exception.business.fee.serviceexception'))
                else:
                    wallet_address_list = json.loads(resp.text)

                service_url = get_env_var(
                    'service.url') + '/address/?wallet_id=' + str(wallet_id)
                print('service_url for  address', service_url)
                resp = requests.get(service_url, auth=service_auth)
                print('received status code for address resp',
                      resp.status_code)
                if resp.status_code != 200:
                    private_input_address_list = json.loads(resp.text)
                    return JsonResponse(private_input_address_list, safe=False)
                else:
                    private_input_address_list = json.loads(resp.text)
                    blocks = 2
                    fee_per_kb = 0
                    if network == 'bitcoin':
                        fee_per_kb = btc_srv.estimatefee(blocks)
                    elif network == 'litecoin':
                        fee_per_kb = ltc_srv.estimatefee(blocks)

                    print('Fee per kb %s' % (str(fee_per_kb)))

                    t = self.create_transaction(wallet_address_list,
                                                private_input_address_list,
                                                output_address, change_address,
                                                send_amount, fee_per_kb,
                                                network)

                    return JsonResponse(t.as_dict(), safe=False)

            else:
                raise ValidationError(
                    get_env_var('exception.validation.fee.no_coin_type'))
        except ServiceException as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(e)
        except Exception as e:
            track = traceback.format_exc()
            print(track)
            return HttpResponse(status=404)
Ejemplo n.º 10
0
    def getunspent(self, wallet_address_list, list, withsum, network):
        try:
            if network == 'litecoin':
                flattent_address_list = []
                final_balance = 0
                for list in list:
                    if len(list) > 0:
                        address_list = list.get('txs')
                        #flatten the list

                        for wl in wallet_address_list:
                            for adr_list in address_list if address_list else [] :
                                print('adr_list', adr_list)
                                for address in adr_list.get('addresses'):
                                    print('address', address, 'wl', wl)
                                    if (address and address == wl):
                                        print(
                                            'match -------------------------------'
                                        )
                                        count = 0
                                        for out in adr_list.get('outputs'):
                                            print(
                                                'match ----------------------------'
                                                + str(out))
                                            add_row = {}
                                            add_row['txid'] = adr_list.get(
                                                'hash')
                                            add_row['vout'] = count
                                            add_row['address'] = out.get(
                                                'addresses')[0] if out.get(
                                                    'addresses') else ''
                                            print('add_row-----------',
                                                  add_row)
                                            count = count + 1
                                            flattent_address_list.append(
                                                add_row)
                                            print(
                                                '\nflattent_address_list-----------',
                                                flattent_address_list)

                    if withsum:
                        final_balance = final_balance + (
                            list.get('final_balance')
                            if list.get('final_balance') else 0)

                if withsum:
                    flattent_address_list.append(
                        {"toal_unspent": final_balance})

            elif network == 'bitcoin':
                if len(list) > 0:
                    address_list = list['txs']
                    # flatten the list
                    flattent_address_list = []
                    for wl in wallet_address_list:
                        for adr_list in address_list:
                            for in_txn in adr_list.get('inputs'):
                                #if (in_txn.get('prev_out') and in_txn.get('prev_out').get('addr') == wl):
                                for out in adr_list.get('out'):
                                    if (out and out.get('addr') == wl):
                                        add_row = {}
                                        add_row['txid'] = adr_list.get('hash')
                                        add_row['vout'] = out.get('n')
                                        add_row['address'] = out.get('addr')
                                        flattent_address_list.append(add_row)

                if withsum and list.get('wallet'):
                    flattent_address_list.append({
                        "toal_unspent":
                        list.get('wallet').get('final_balance')
                    })

            return flattent_address_list

        except Exception as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(e)
Ejemplo n.º 11
0
    def get(self, request, wallet_id):
        """
        Retrieve, update or delete a code snippet.
        """
        try:
            print('enter txn')
            txn = Txn.txn_list_wallet(db_uri=db_uri, wallet_id=wallet_id)

            print('Started ' + self.__class__.__name__ + ' get method')

            network = request.GET.get('network')

            print('Started ', self.__class__.__name__,
                  '  wallet_id=%s, network=%s ' % (str(wallet_id), network))
            address_list = []
            if wallet_id and network:
                wallet = HDWallet(wallet_id, db_uri=db_uri)
                wallet_address_list = wallet.addresslist()
                if network == 'bitcoin':
                    address_list = '|'.join(
                        [str(a) for a in wallet_address_list])
                    block_service_url = get_env_var(
                        'blockchain.service.url'
                    ) + '/multiaddr?active=' + address_list
                    print('service_url for get balance', block_service_url)
                    resp = requests.get(block_service_url)
                    print('\nreceived for blcokchain multiaddr resp',
                          resp.status_code)
                    address_list = json.loads(resp.text)
                    address_list = self.getBitcoinTxn(address_list)
                    return JsonResponse(address_list, safe=False)
                elif network == 'litecoin':
                    address_list = ';'.join(
                        [str(a) for a in wallet_address_list])
                    blockcypher_service_url = get_env_var(
                        'blockcypher.service.url'
                    ) + '/v1/ltc/main/addrs/' + address_list + '/full?token=' + get_env_var(
                        'blockcypher.service.token')
                    print('service_url for unspent balance',
                          blockcypher_service_url)
                    resp = requests.get(blockcypher_service_url)
                    print('\nreceived for blockcypher balance resp',
                          resp.status_code)
                    address_list = json.loads(resp.text)
                    address_list = self.getLitecoinTxn(address_list)
                    print('address_list----------', address_list)
                    return JsonResponse(address_list, safe=False)
            else:
                raise ValidationError(
                    get_env_var(
                        'exception.validation.txn.no_wallet_or_no_network'))
        except WalletError as e:
            track = traceback.format_exc()
            print(track)
            raise e
        except ServiceException as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(e)
        except Exception as e:
            track = traceback.format_exc()
            print(track)
            raise ServiceException(
                get_env_var('exception.business.txn.serviceexception'))

            return JsonResponse(txn, safe=False)

        except Txn.DoesNotExist:
            return HttpResponse(status=404)
Ejemplo n.º 12
0
    def post(self, request):
        """
        Retrieve, update or delete a code snippet.
        """
        print("enter sign and send")
        try:
            data = JSONParser().parse(request)
            wallet_id = data.get('wallet_id')
            username = data.get('username')
            hex = data.get('hex')
            coin_type = data.get('type')

            txn_data = {}
            txn_data['username'] = data.get('username')
            txn_data['type'] = data.get('txn_type')
            txn_data['status'] = data.get('status')
            txn_data['source'] = data.get('source')
            txn_data['source_amount'] = data.get('source_amount')
            txn_data['source_currency'] = data.get('source_currency')
            txn_data['destination'] = data.get('destination')
            txn_data['destination_amount'] = data.get('destination_amount')
            txn_data['destination_currency'] = data.get('destination_currency')
            txn_data['message'] = data.get('message')
            txn_data['includes_fee'] = data.get('includes_fee')

            print(' txn with data' + str(data))

            if username and coin_type and hex:
                print(username + "username")
                service_url = get_env_var(
                    'service.url') + '/key/?wallet_id=' + str(
                        wallet_id) + '&type=' + coin_type
                print(service_url + "service_url")
                resp = requests.get(service_url, auth=service_auth)
                if resp.status_code != 200:
                    print('address response', resp.text)
                    raise ServiceException(
                        get_env_var(
                            'exception.business.sign.serviceexception'))
                else:
                    print('address response', resp.text)
                    response_list = json.loads(resp.text)
                    sign_dict_str = self.sign_txn(hex, response_list)
                    print('sign request ' + sign_dict_str)
                    url = get_url(coin_type, "signtxn")
                    # url = 'https://66f49c90-24e2-4d2b-891d-5746233c8ae7.mock.pstmn.io/sign'
                    if coin_type == 'BTC':
                        resp = requests.post(url,
                                             auth=btc_auth,
                                             data=sign_dict_str)
                    elif coin_type == 'LTC':
                        resp = requests.post(url,
                                             auth=ltc_auth,
                                             data=sign_dict_str)

                    print(resp.status_code)
                    if resp.status_code != 200:
                        print('sign response ' + resp.text)
                        raise ServiceException(
                            get_env_var(
                                'exception.business.sign.serviceexception'))
                    else:
                        print('sign response ' + resp.text)
                        send_dict = json.loads(resp.text)
                        send_dict_str = self.send_txn(hex, send_dict)
                        url = get_url(coin_type, 'sendtxn')

                        # url = 'https://66f49c90-24e2-4d2b-891d-5746233c8ae7.mock.pstmn.io/send'
                        if coin_type == 'BTC':
                            resp = requests.post(url,
                                                 auth=btc_auth,
                                                 data=send_dict_str)
                        elif coin_type == 'LTC':
                            resp = requests.post(url,
                                                 auth=ltc_auth,
                                                 data=send_dict_str)

                        print(resp.status_code)
                        if resp.status_code != 200:
                            print('send error response ' + resp.text +
                                  ' with status code' + str(resp.status_code))
                            Util.sendMessage('send', '/queue/test')
                            raise ServiceException(
                                get_env_var(
                                    'exception.business.send.serviceexception')
                            )
                        else:
                            print('send suucess response ' + resp.text +
                                  ' with status code' + str(resp.status_code))
                            Util.sendMessage('send', '/queue/test')
                            if resp.text:
                                print('saving in txn')
                                txn_data['txn_id'] = resp.text
                                serializer = TxnSerializer(data=txn_data)
                                if serializer.is_valid():
                                    serializer.save()
                                else:
                                    print('data invalid')
                                    return JsonResponse(serializer.errors,
                                                        status=400)
                                return JsonResponse(serializer.data,
                                                    status=201,
                                                    safe=False)
                            else:
                                raise ServiceException(
                                    get_env_var(
                                        'exception.business.send.serviceexception'
                                    ))

            else:
                raise ValidationError(
                    get_env_var(
                        'exception.validation.sign.no_user_or_no_coin_type_or_no_hex'
                    ))
        except Exception as e:
            track = traceback.format_exc()
            print(track)
            print("error" + str(e))
            raise e