예제 #1
0
def address_disambiguation(request, address):
    """
    When the user tried to lookup a currency that has a duplicate address byte
    take them to this page where they can choose which currency they meant.
    """
    guess_currency_result = guess_currency_from_address(address)
    balances = {}
    for crypto, name in guess_currency_result:
        try:
            balance = get_address_balance(crypto, address)
        except Exception as exc:
            balance = str(exc)

        balances[crypto.upper()] = {'balance': balance, 'name': name}

    return TemplateResponse(request, "address_disambiguation.html", {
        'balances': balances,
        'address': address,
    })
예제 #2
0
def address_disambiguation(request, address):
    """
    When the user tried to lookup a currency that has a duplicate address byte
    take them to this page where they can choose which currency they meant.
    """
    guess_currency_result = guess_currency_from_address(address)
    balances = {}
    for crypto, name in guess_currency_result:
        try:
            balance = get_address_balance(crypto, address)
        except Exception as exc:
            balance = str(exc)

        balances[crypto.upper()] = {'balance': balance, 'name': name}

    return TemplateResponse(request, "address_disambiguation.html", {
        'balances': balances,
        'address': address,
    })
예제 #3
0
    def get_tipped_value(self):
        """
        Check the blokchain to see how many tips have been collected.
        """
        if not self.address:
            return 0

        cache = caches['default']
        price = cache.get('btc-price')
        if not price:
            price, source = get_current_price('btc', 'usd')
            cache.set('btc-price', price)

        status_balance = cache.get(self.address)
        if not status_balance:
            balance = get_address_balance('btc', self.address)
            cache.set(self.address, ['OK', balance])
        else:
            status, balance = status_balance

        return balance * price
예제 #4
0
    def get_tipped_value(self):
        """
        Check the blokchain to see how many tips have been collected.
        """
        if not self.address:
            return 0

        cache = caches['default']
        price = cache.get('btc-price')
        if not price:
            price, source = get_current_price('btc', 'usd')
            cache.set('btc-price', price)

        status_balance = cache.get(self.address)
        if not status_balance:
            balance = get_address_balance('btc', self.address)
            cache.set(self.address, ['OK', balance])
        else:
            status, balance = status_balance

        return balance * price
def fetch_wallet_balances(wallets, fiat, **modes):
    """
    Wallets must be list of two item lists. First item is crypto, second item
    is the address. example:

    [
        ['btc', '1PZ3Ps9RvCmUW1s1rHE25FeR8vtKUrhEai'],
        ['ltc', 'Lb78JDGxMcih1gs3AirMeRW6jaG5V9hwFZ']
    ]
    """
    price_fetch = set([x[0] for x in wallets])
    balances = {}
    prices = {}

    fetch_length = len(wallets) + len(price_fetch)

    if not modes.get('async', False):
        # synchronous fetching
        for crypto in price_fetch:
            prices[crypto] = get_current_price(crypto,
                                               fiat,
                                               report_services=True,
                                               **modes)

        for crypto, address in wallets:
            balances[address] = get_address_balance(crypto, address.strip(),
                                                    **modes)

    else:
        # asynchronous fetching
        if modes.get('verbose', False):
            print("Need to make", fetch_length, "external calls")

        with futures.ThreadPoolExecutor(max_workers=int(fetch_length /
                                                        2)) as executor:
            future_to_key = dict((executor.submit(
                get_current_price, crypto, fiat, report_services=True, **
                modes), crypto) for crypto in price_fetch)

            future_to_key.update(
                dict((executor.submit(get_address_balance, crypto,
                                      address.strip(), **modes), address)
                     for crypto, address in wallets))

            done, not_done = futures.wait(future_to_key,
                                          return_when=futures.FIRST_EXCEPTION)
            if len(not_done) > 0:
                raise not_done.pop().exception()

            for future in done:
                key = future_to_key[future]
                if len(
                        key
                ) > 5:  # this will break if a crypto symbol is longer than 5 chars.
                    which = balances
                else:
                    which = prices

                res = future.result()
                which[key] = res

    ret = []

    for crypto, address in wallets:
        crypto_value = balances[address]
        sources, fiat_price = prices[crypto]
        ret.append({
            'crypto': crypto,
            'address': address,
            'crypto_value': crypto_value,
            'fiat_value': crypto_value * fiat_price,
            'conversion_price': fiat_price,
            'price_source': sources[0].name
        })

    return ret
예제 #6
0
파일: wallet.py 프로젝트: cst13/canstel
def fetch_wallet_balances(wallets, fiat, **modes):
    """
    Wallets must be list of two item lists. First item is crypto, second item
    is the address. example:

    [
        ['btc', '1ACMqsyyuoggTpiHqGePuFSVzk54wfZWDv'],
        ['ltc', 'Lb78JDGxMcih1gs3AirMeRW6jaG5V9hwFZ']
    ]
    """
    price_fetch = set([x[0] for x in wallets])
    balances = {}
    prices = {}

    fetch_length = len(wallets) + len(price_fetch)

    helpers = {fiat.lower(): {}}
    if not modes.get('async', False):
        # synchronous fetching
        for crypto in price_fetch:
            try:
                p = get_current_price(
                    crypto, fiat, helper_prices=helpers, report_services=True, **modes
                )
                prices[crypto] = {'price': p}
                if crypto in ['btc', 'ltc', 'doge', 'uno']:
                    helpers[fiat.lower()][crypto] = p
            except NoService as exc:
                prices[crypto] = {'error': str(exc)}

        for crypto, address in wallets:
            if address.replace('.', '').isdigit():
                balances[address] = {'balance': float(address)}
                continue

            try:
                balances[address] = {'balance': get_address_balance(crypto, address.strip(), **modes)}
            except NoService as exc:
                balances[address] = {'error': str(exc)}

    else:
        # asynchronous fetching
        if modes.get('verbose', False):
            print("Need to make", fetch_length, "external calls")

        with futures.ThreadPoolExecutor(max_workers=int(fetch_length / 2)) as executor:
            future_to_key = dict(
                (executor.submit(
                    get_current_price, crypto, fiat, report_services=True, **modes
                ), crypto) for crypto in price_fetch
            )

            future_to_key.update(dict(
                (executor.submit(
                    get_address_balance, crypto, address.strip(), **modes
                ), address) for crypto, address in wallets
            ))

            done, not_done = futures.wait(future_to_key, return_when=futures.ALL_COMPLETED)
            if len(not_done) > 0:
                print (not_done)
                import debug
                raise Exception("Broke") #not_done.pop().exception()

            for future in done:
                key = future_to_key[future]
                if len(key) > 5: # this will break if a crypto symbol is longer than 5 chars.
                    which = balances
                else:
                    which = prices

                res = future.result()
                which[key] = res

    ret = []

    for crypto, address in wallets:
        error = None
        if 'balance' in balances[address]:
            crypto_value = balances[address]['balance']
        else:
            crypto_value = 0
            error = balances[address]['error']

        if 'price' in prices[crypto]:
            sources, fiat_price = prices[crypto]['price']
        else:
            sources, fiat_price = [None], 0
            error = prices[crypto]['error']

        ret.append({
            'crypto': crypto,
            'address': address,
            'crypto_value': crypto_value,
            'fiat_value': (crypto_value or 0) * (fiat_price or 0),
            'conversion_price': fiat_price,
            'price_source': sources[0].name,
            'error': error
        })

    return ret
예제 #7
0
def fetch_wallet_balances(wallets, fiat, **modes):
    """
    Wallets must be list of two item lists. First item is crypto, second item
    is the address. example:

    [
        ['btc', '1PZ3Ps9RvCmUW1s1rHE25FeR8vtKUrhEai'],
        ['ltc', 'Lb78JDGxMcih1gs3AirMeRW6jaG5V9hwFZ']
    ]
    """
    price_fetch = set([x[0] for x in wallets])
    balances = {}
    prices = {}

    fetch_length = len(wallets) + len(price_fetch)

    helpers = {fiat.lower(): {}}
    if not modes.get('async', False):
        # synchronous fetching
        for crypto in price_fetch:
            try:
                p = get_current_price(
                    crypto, fiat, helper_prices=helpers, report_services=True, **modes
                )
                prices[crypto] = {'price': p}
                if crypto in ['btc', 'ltc', 'doge', 'uno']:
                    helpers[fiat.lower()][crypto] = p
            except NoService as exc:
                prices[crypto] = {'error': str(exc)}

        for crypto, address in wallets:
            if address.replace('.', '').isdigit():
                balances[address] = {'balance': float(address)}
                continue

            try:
                balances[address] = {'balance': get_address_balance(crypto, address.strip(), **modes)}
            except NoService as exc:
                balances[address] = {'error': str(exc)}

    else:
        # asynchronous fetching
        if modes.get('verbose', False):
            print("Need to make", fetch_length, "external calls")

        with futures.ThreadPoolExecutor(max_workers=int(fetch_length / 2)) as executor:
            future_to_key = dict(
                (executor.submit(
                    get_current_price, crypto, fiat, report_services=True, **modes
                ), crypto) for crypto in price_fetch
            )

            future_to_key.update(dict(
                (executor.submit(
                    get_address_balance, crypto, address.strip(), **modes
                ), address) for crypto, address in wallets
            ))

            done, not_done = futures.wait(future_to_key, return_when=futures.ALL_COMPLETED)
            if len(not_done) > 0:
                print (not_done)
                import debug
                raise Exception("Broke") #not_done.pop().exception()

            for future in done:
                key = future_to_key[future]
                if len(key) > 5: # this will break if a crypto symbol is longer than 5 chars.
                    which = balances
                else:
                    which = prices

                res = future.result()
                which[key] = res

    ret = []

    for crypto, address in wallets:
        error = None
        if 'balance' in balances[address]:
            crypto_value = balances[address]['balance']
        else:
            crypto_value = 0
            error = balances[address]['error']

        if 'price' in prices[crypto]:
            sources, fiat_price = prices[crypto]['price']
        else:
            sources, fiat_price = [], 0
            error = prices[crypto]['error']

        ret.append({
            'crypto': crypto,
            'address': address,
            'crypto_value': crypto_value,
            'fiat_value': (crypto_value or 0) * (fiat_price or 0),
            'conversion_price': fiat_price,
            'price_source': sources[0].name if sources else "None",
            'error': error
        })

    return ret
예제 #8
0
def _make_moneywagon_fetch(Service,
                           service_mode,
                           service_id,
                           address,
                           addresses,
                           xpub,
                           currency,
                           currency_name,
                           block_args,
                           fiat=None,
                           txid=None,
                           random_mode=False,
                           **k):

    if Service:
        if Service.supported_cryptos and currency not in Service.supported_cryptos:
            raise Exception("%s not supported for %s with %s" %
                            (currency_name, service_mode, Service.name))
        services = [Service]
    else:
        services = []  # fallback mode

    modes = dict(report_services=True,
                 services=services,
                 random=random_mode,
                 timeout=10.0,
                 verbose=settings.DEBUG)

    if service_id.startswith("paranoid"):
        modes['paranoid'] = int(service_id[8:])
    elif service_id.startswith("average"):
        modes['average'] = int(service_id[7:])
    elif service_id.startswith("private"):
        modes['private'] = int(service_id[7:])
        if modes['private'] > 30:
            raise Exception("Private mode maximum of 30")

    if address:
        modes['address'] = address
    elif addresses:
        modes['addresses'] = addresses.split(',')

    if service_mode == 'current_price':
        used_services, price = get_current_price(currency, fiat, **modes)
        PriceTick.record_price(price, currency, fiat, used_services[0].name)
        ret = {'current_price': price}
    elif service_mode == 'address_balance':
        used_services, balance = get_address_balance(currency, **modes)
        ret = {'balance': balance}
    elif service_mode == 'unspent_outputs':
        used_services, utxos = get_unspent_outputs(currency, **modes)
        ret = {'utxos': sorted(utxos, key=lambda x: x['output'])}
    elif service_mode == 'historical_transactions':
        used_services, txs = get_historical_transactions(currency, **modes)
        ret = {'transactions': sorted(txs, key=lambda x: x['txid'])}
    elif service_mode == 'single_transaction':
        used_services = None
        tx = CachedTransaction.fetch_full_tx(currency, txid=txid, fiat=fiat)
        ret = {'transaction': tx}
    elif service_mode == 'get_block':
        if block_args['block_number']:
            block_args['block_number'] = int(block_args['block_number'])
        modes.update(block_args)
        used_services, block_data = get_block(currency, **modes)
        ret = {'block': block_data}
    elif service_mode == 'optimal_fee':
        used_services, fee = get_optimal_fee(currency, 1024, **modes)
        ret = {'optimal_fee_per_KiB': fee}
    else:
        raise Exception("Unsupported Service mode")

    if not used_services:
        pass  # private mode does not return services
    elif len(used_services) == 1:
        s = used_services[0]
        if s:
            ret['url'] = s.last_url
            ret['raw_response'] = s.last_raw_response.json()
            ret['service_name'] = s.name
            ret['service_id'] = s.service_id
    else:
        ret['services'] = [{
            'name': s.name,
            'id': s.service_id,
            'raw_response': s.last_raw_response.json()
        } for s in used_services]

    return ret
예제 #9
0
def _make_moneywagon_fetch(Service, service_mode, service_id, address, addresses,
    xpub, currency, currency_name, block_args, fiat=None, txid=None, random_mode=False, **k):

    if Service:
        if Service.supported_cryptos and currency not in Service.supported_cryptos:
            raise Exception("%s not supported for %s with %s" % (
                currency_name, service_mode, Service.name
            ))
        services = [Service]
    else:
        services = [] # fallback mode

    modes = dict(
        report_services=True,
        services=services,
        random=random_mode,
        timeout=10.0,
        verbose=settings.DEBUG
    )

    if service_id.startswith("paranoid"):
        modes['paranoid'] = int(service_id[8:])
    elif service_id.startswith("average"):
        modes['average'] = int(service_id[7:])
    elif service_id.startswith("private"):
        modes['private'] = int(service_id[7:])
        if modes['private'] > 30:
            raise Exception("Private mode maximum of 30")

    if address:
        modes['address'] = address
    elif addresses:
        modes['addresses'] = addresses.split(',')

    if service_mode == 'current_price':
        used_services, price = get_current_price(currency, fiat, **modes)
        PriceTick.record_price(price, currency, fiat, used_services[0].name)
        ret = {'current_price': price}
    elif service_mode == 'address_balance':
        used_services, balance = get_address_balance(currency, **modes)
        ret = {'balance': balance}
    elif service_mode == 'unspent_outputs':
        used_services, utxos = get_unspent_outputs(currency, **modes)
        ret = {'utxos': sorted(utxos, key=lambda x: x['output'])}
    elif service_mode == 'historical_transactions':
        used_services, txs = get_historical_transactions(currency, **modes)
        ret = {'transactions': sorted(txs, key=lambda x: x['txid'])}
    elif service_mode == 'single_transaction':
        used_services = None
        tx = CachedTransaction.fetch_full_tx(currency, txid=txid, fiat=fiat)
        ret = {'transaction': tx}
    elif service_mode == 'get_block':
        if block_args['block_number']:
            block_args['block_number'] = int(block_args['block_number'])
        modes.update(block_args)
        used_services, block_data = get_block(currency, **modes)
        ret = {'block': block_data}
    elif service_mode == 'optimal_fee':
        used_services, fee = get_optimal_fee(currency, 1024, **modes)
        ret = {'optimal_fee_per_KiB': fee}
    else:
        raise Exception("Unsupported Service mode")

    if not used_services:
        pass # private mode does not return services
    elif len(used_services) == 1:
        s = used_services[0]
        if s:
            ret['url'] = s.last_url
            ret['raw_response'] = s.last_raw_response.json()
            ret['service_name'] = s.name
            ret['service_id'] = s.service_id
    else:
        ret['services'] = [
            {'name': s.name, 'id': s.service_id, 'raw_response': s.last_raw_response.json()}
            for s in used_services
        ]

    return ret
예제 #10
0
def fetch_wallet_balances(wallets, fiat, **modes):
    """
    Wallets must be list of two item lists. First item is crypto, second item
    is the address. example:

    [
        ['btc', '1PZ3Ps9RvCmUW1s1rHE25FeR8vtKUrhEai'],
        ['ltc', 'Lb78JDGxMcih1gs3AirMeRW6jaG5V9hwFZ']
    ]
    """
    price_fetch = set([x[0] for x in wallets])
    balances = {}
    prices = {}

    fetch_length = len(wallets) + len(price_fetch)

    if not modes.get('async', False):
        # synchronous fetching
        for crypto in price_fetch:
            prices[crypto] = get_current_price(crypto, fiat, **modes)

        for crypto, address in wallets:
            balances[address] = get_address_balance(crypto, address.strip(), **modes)

    else:
        # asynchronous fetching
        if modes.get('verbose', False):
            print("Need to make", fetch_length, "external calls")

        with futures.ThreadPoolExecutor(max_workers=int(fetch_length / 2)) as executor:
            future_to_key = dict(
                (executor.submit(
                    get_current_price, crypto, fiat, **modes
                ), crypto) for crypto in price_fetch
            )

            future_to_key.update(dict(
                (executor.submit(
                    get_address_balance, crypto, address.strip(), **modes
                ), address) for crypto, address in wallets
            ))

            done, not_done = futures.wait(future_to_key, return_when=futures.FIRST_EXCEPTION)
            if len(done) > 0:
                raise not_done.pop().exception()

            for future in done:
                key = future_to_key[future]
                if len(key) > 5: # this will break if a crypto symbol is longer than 5 chars.
                    which = balances
                else:
                    which = prices

                res = future.result()
                which[key] = res

    ret = []
    for crypto, address in wallets:
        crypto_value = balances[address]
        fiat_price, source = prices[crypto]
        ret.append({
            'crypto': crypto,
            'address': address,
            'crypto_value': crypto_value,
            'fiat_value': crypto_value * fiat_price,
            'conversion_price': fiat_price,
            'price_source': source
        })

    return ret