Esempio n. 1
0
def get_last_blocks(count):
    client = BiblePayRpcClient('main')

    current_height = client.getblockcount()

    last_blocks = []
    # get current and 5 other blocks
    for height in range(current_height, current_height - count, -1):
        block_hash = client.getblockhash(height)

        last_blocks.append({
            'height': height,
            'block_hash': block_hash,
        })

    return last_blocks
Esempio n. 2
0
def update_masternodes():
    client = BiblePayRpcClient('main')

    for mn in client.masternode_list_full():
        masternode, created = Masternode.objects.get_or_create(
            txid=mn['txid'],
            defaults={
                'status': mn['status'],
                'version': mn['version'],
                'address': mn['address'],
            })

        masternode.status = mn['status']
        masternode.version = mn['version']
        masternode.address = mn['address']
        masternode.last_seen_at = timezone.now()
        masternode.save()
Esempio n. 3
0
def ajax_utxreport(request, cpid):
    utxreport = []

    client = BiblePayRpcClient('main')
    report = client.utxoreport(cpid)

    prev_day = ''
    for entry in report:
        for s in ['(', ')', '[', ']', 'TXID=']:
            entry = entry.replace(s, '')

        data = entry.split(' ')

        if len(data) < 4:  # some other output in the json
            continue

        d = data[1].split('-')
        day = datetime.date(int(d[2]), int(d[0]), int(d[1]))

        utxreport.append({
            'block': data[0],
            'day': day.strftime("%A %d. %B %Y"),
            'time': data[2],
            'utxo_weight': data[3],
            'transaction_id': data[5],
            'new_day': False,
        })

        utxreport.sort(key=lambda e: e['block'], reverse=True)

    # now we add a day info
    prev_day = ''
    for i, item in enumerate(utxreport):
        new_day = False
        if item['day'] != prev_day:
            prev_day = item['day']
            new_day = True

        utxreport[i]['new_day'] = new_day

    return render(request, 'podc/ajax_utxoreport.html',
                  {'utxreport': utxreport})
Esempio n. 4
0
    def render(self, context, instance, placeholder):
        context = super().render(context, instance, placeholder)

        next_budget = 0
        try:
            client = BiblePayRpcClient('main')
            next_budget = client.getboincinfo()['NextSuperblockBudget']
        except:
            raise

        next_superblock = 0
        try:
            client = BiblePayRpcClient('main')
            next_superblock = client.getboincinfo()['NextSuperblockHeight']
        except:
            pass

        context.update({
            'team_members':
            Leaderboard.objects.all().count(),
            'next_budget':
            next_budget,
            'next_superblock':
            next_superblock,
            'leaderboard':
            Leaderboard.objects.all().order_by('-rac')[0:3]
        })
        return context
Esempio n. 5
0
def get_masternode_count():
    """ asks the biblepay client for the count of masternodes """

    count = -1
    try:
        client = BiblePayRpcClient('main')

        count = 0
        for key, value in client.rpc.masternodelist().items():
            count += 1
    except:
        pass

    return count
Esempio n. 6
0
def estimate_blockhittime(height):
    """ we try to calculate when the block will hit.
        For that, we get the current block, 500 blocks int he past, take the time between them
        and look how much time it is in the future with the same time-per-block """

    client = BiblePayRpcClient('main')

    current_height = client.getblockcount()

    dt = None
    if current_height >= height:  # already at or after the superblock? then use that time
        block_hash = client.getblockhash(height)
        block = client.getblock(block_hash)
        dt = datetime.datetime.utcfromtimestamp(block['mediantime'])
    else:
        past_block_sub = 200

        block_hash = client.getblockhash(current_height)
        block = client.getblock(block_hash)
        dt_current = datetime.datetime.utcfromtimestamp(block['mediantime'])

        past_block = current_height - past_block_sub

        block_hash = client.getblockhash(past_block)
        block = client.getblock(block_hash)
        dt_past = datetime.datetime.utcfromtimestamp(block['mediantime'])

        # the avg time between two blocks is the result
        diff = (dt_current - dt_past) / past_block_sub

        # now we count how many blocks the required block is in the future
        diff_count = height - current_height

        # and we add the avgtimer per block * future blocks until the required block
        # to "now"
        dt = datetime.datetime.now() + (diff * diff_count)

    return dt
Esempio n. 7
0
def get_last_transactions(count=10):
    client = BiblePayRpcClient('main')

    height = client.getblockcount()

    current_tx = 0
    last_transaction = []

    run = True
    while run:
        block_hash = client.getblockhash(height)
        block_data = client.getblock(block_hash)

        for tx in block_data.get('tx', []):
            tx_data = client.getrawtransaction(tx, True)

            amount = 0
            for t in tx_data['vout']:
                amount += t['value']

            last_transaction.append({
                'txid':
                tx_data['txid'],
                'height':
                height,
                'block_hash':
                block_hash,
                'recipient_count':
                len(tx_data['vout']),
                'amount':
                amount,
                'timestamp':
                datetime.datetime.fromtimestamp(int(tx_data['time'])),
            })

            current_tx += 1
            if current_tx > count:
                run = False
                break

        height -= 1

    return last_transaction
Esempio n. 8
0
def import_superblock(import_height=None):
    """ Imports the data for the last superblock from the main pool """

    pool_url = 'http://pool.biblepay.org/action.aspx?action=api_superblock&uncache=' + str(
        randint(0, 99999999))
    r = requests.get(pool_url)

    # converts the result to a list/dict combination.
    # we don't catch any errors here, as the task should fail if this is not ok
    content = pool_cvs_to_list(r.content.decode('utf-8'))

    # first, we need to know which block to import, if none was given
    if import_height is None:
        height = 0
        for entry in content:
            if int(entry['Height']) > height:
                height = int(entry['Height'])
                print(height)
    else:
        height = import_height

    # now we need to find information about our block in the list
    # and find the amount of receivers
    receiver_count = 0
    for entry in content:
        if int(entry['Height']) == height:
            receiver_count += 1
            total_rac = entry['totalrac']

    # no data found? Exit
    if height == 0 or receiver_count == 0:
        return

    # and add some external infos
    client = BiblePayRpcClient('main')
    budget = client.getsuperblockbudget(height)

    # next we create the superblock, if required, and update an existing one
    superblock, created = Superblock.objects.get_or_create(height=height)
    superblock.total_rac = total_rac
    superblock.receiver_count = receiver_count
    superblock.budget = budget
    superblock.save()

    # we need to remove the entries for this block from the receiver list,
    # it there are already entries
    SuperblockReceiver.objects.filter(superblock=superblock).delete()

    # and now we add the new entries
    for entry in content:
        if int(entry['Height']) != height:
            continue

        rosettauser, created = RosettaUser.objects.get_or_create(
            id=entry['rosettaid'], defaults={'username': entry['name']})

        # This is the bbp share the user gets from the budget
        reward = 0
        magnitude = 0
        try:
            magnitude = decimal.Decimal(entry['magnitude'])
        except:
            pass

        if magnitude > 0:
            try:
                reward = decimal.Decimal(superblock.budget) * decimal.Decimal(
                    magnitude / 1000)
            except:
                pass

        receiver = SuperblockReceiver(
            rosettauser=rosettauser,
            superblock=superblock,
            address=entry['address'],
            cpid=entry['cpid'],
            team=entry['team'],
            reward=reward,
            magnitude=magnitude,
            utxo_amount=entry['utxoamount'],  # reversed in the pool
            utxo_weight=entry['utxoweight'],  # reversed in the pool
            task_weight=entry['taskweight'],
            unbanked=entry['unbanked'],
            avg_rac=entry['avgrac'] or 0,
            modified_rac=entry['modifiedrac'] or 0,
            machine_count=entry['MachineCount'] or 0,
            total_procs=entry['TotalProcs'] or 0,
        )
        receiver.save()

        rosettauser.cpid = entry['cpid']
        rosettauser.address = entry['address']
        rosettauser.team = entry['team']
        rosettauser.save()
Esempio n. 9
0
def get_nextsuperblock_proposal_data(network="main", block=None):
    client = BiblePayRpcClient(network)

    # next superblock and budget
    if block is None:
        sbdata = client.getgovernanceinfo()
        next_superblock = int(sbdata['nextsuperblock'])
    else:
        next_superblock = int(block)

    data = {
        'next_superblock': next_superblock,
        'next_budget': int(float(client.getsuperblockbudget(next_superblock))),
    }

    # when do we expect this block?
    data['estimated_time'] = estimate_blockhittime(next_superblock)

    # budget per category
    data['budgets'] = {
        'charity': (data['next_budget'] / 100) * 50,
        'it': (data['next_budget'] / 100) * 25,
        'pr': (data['next_budget'] / 100) * 12.5,
        'p2p': (data['next_budget'] / 100) * 12.5,
    }

    # and all proposals that have not been paid by any superblock but have
    # the approval of at least 10% of all active sanctuaries. This is required to
    # be paid in the next superblock
    data['requested_budgets'] = {
        'total': 0,
        'charity': 0,
        'it': 0,
        'pr': 0,
        'p2p': 0,
        'charity__requested': 0,
        'it__requested': 0,
        'pr__requested': 0,
        'p2p__requested': 0,
        'unspend': 0,
    }

    if block is None:
        proposals = Proposal.objects.filter(network=network,
                                            height__isnull=True,
                                            active=True)
    else:
        proposals = Proposal.objects.filter(network=network,
                                            height=block,
                                            active=True)

    for proposal in proposals:
        if proposal.expense_type == 'unknown':
            continue

        data['requested_budgets'][proposal.expense_type +
                                  '__requested'] += proposal.amount
        if proposal.is_fundable():
            data['requested_budgets'][proposal.expense_type] += proposal.amount
            data['requested_budgets']['total'] += proposal.amount

    data['requested_budgets'][
        'unspend'] = data['next_budget'] - data['requested_budgets']['total']
    if data['requested_budgets']['unspend'] < 0:
        data['requested_budgets']['unspend'] = 0

    # for the graph, we need the highest value in the budgets or requested_budget
    data['highest_budget_value'] = 0
    check = [data['requested_budgets'], data['budgets']]
    for c in check:
        for k, v in c.items():
            if k != 'total' and v > data['highest_budget_value']:
                data['highest_budget_value'] = int(v)

    return data