Ejemplo n.º 1
0
def check(dashd, net):
    if not (yield net.PARENT.RPC_CHECK(dashd)):
        print >> sys.stderr, "    Check failed! Make sure that you're connected to the right dashd with --dashd-rpc-port!"
        raise deferral.RetrySilentlyException()
    if not net.VERSION_CHECK((yield dashd.rpc_getinfo())['version']):
        print >> sys.stderr, '    Dash version too old! Upgrade to 0.11.0.11 or newer!'
        raise deferral.RetrySilentlyException()
Ejemplo n.º 2
0
def check(bitcoind, net):
    if not (yield net.PARENT.RPC_CHECK(bitcoind)):
        print >> sys.stderr, "    Check failed! Make sure that you're connected to the right bitcoind with --bitcoind-rpc-port!"
        raise deferral.RetrySilentlyException()

    version_check_result = net.VERSION_CHECK(
        (yield bitcoind.rpc_getinfo())['version'])
    if version_check_result == True: version_check_result = None  # deprecated
    if version_check_result == False:
        version_check_result = 'Coin daemon too old! Upgrade!'  # deprecated
    if version_check_result is not None:
        print >> sys.stderr, '    ' + version_check_result
        raise deferral.RetrySilentlyException()

    try:
        blockchaininfo = yield bitcoind.rpc_getblockchaininfo()
        softforks_supported = set(
            item['id'] for item in blockchaininfo.get('softforks', []))
        try:
            softforks_supported |= set(
                item['id']
                for item in blockchaininfo.get('bip9_softforks', []))
        except TypeError:  # https://github.com/bitcoin/bitcoin/pull/7863
            softforks_supported |= set(
                item for item in blockchaininfo.get('bip9_softforks', []))
    except jsonrpc.Error_for_code(-32601):  # Method not found
        softforks_supported = set()
    if getattr(net, 'SOFTFORKS_REQUIRED', set()) - softforks_supported:
        print 'Coin daemon too old! Upgrade!'
        raise deferral.RetrySilentlyException()
Ejemplo n.º 3
0
def check(axed, net):
    if not (yield net.PARENT.RPC_CHECK(axed)):
        print >> sys.stderr, "    Check failed! Make sure that you're connected to the right axed with --axed-rpc-port!"
        raise deferral.RetrySilentlyException()
    if not net.VERSION_CHECK((yield axed.rpc_getnetworkinfo())['version']):
        print >> sys.stderr, '    axe version too old! Upgrade to 0.12.2.0 or newer!'
        raise deferral.RetrySilentlyException()
Ejemplo n.º 4
0
def check(bitcoind, net):
    if not (yield net.PARENT.RPC_CHECK(bitcoind)):
        print >> sys.stderr, "    Check failed! Make sure that you're connected to the right bitcoind with --bitcoind-rpc-port!"
        raise deferral.RetrySilentlyException()
    if not net.VERSION_CHECK((yield bitcoind.rpc_getinfo())['version']):
        print >> sys.stderr, '    Bitcoin version too old! Upgrade to 0.6.4 or newer!'
        raise deferral.RetrySilentlyException()
Ejemplo n.º 5
0
def check(bitcoind, net, args):
    if not (yield net.PARENT.RPC_CHECK(bitcoind)):
        print >>sys.stderr, "    Check failed! Make sure that you're connected to the right bitcoind with --bitcoind-rpc-port, and that it has finished syncing!"
        raise deferral.RetrySilentlyException()
    
    version_check_result = net.VERSION_CHECK((yield bitcoind.rpc_getnetworkinfo())['version'])
    if version_check_result == True: version_check_result = None # deprecated
    if version_check_result == False: version_check_result = 'Coin daemon too old! Upgrade!' # deprecated
    if version_check_result is not None:
        print >>sys.stderr, '    ' + version_check_result
        raise deferral.RetrySilentlyException()
    
    try:
        blockchaininfo = yield bitcoind.rpc_getblockchaininfo()
        softforks_supported = set(item['id'] for item in blockchaininfo.get('softforks', []))
        try:
            softforks_supported |= set(item['id'] for item in blockchaininfo.get('bip9_softforks', []))
        except TypeError: # https://github.com/bitcoin/bitcoin/pull/7863
            softforks_supported |= set(item for item in blockchaininfo.get('bip9_softforks', []))
    except jsonrpc.Error_for_code(-32601): # Method not found
        softforks_supported = set()
    unsupported_forks = getattr(net, 'SOFTFORKS_REQUIRED', set()) - softforks_supported
    if unsupported_forks:
        print "You are running a coin daemon that does not support all of the "
        print "forking features that have been activated on this blockchain."
        print "Consequently, your node may mine invalid blocks or may mine blocks that"
        print "are not part of the Nakamoto consensus blockchain.\n"
        print "Missing fork features:", ', '.join(unsupported_forks)
        if not args.allow_obsolete_bitcoind:
            print "\nIf you know what you're doing, this error may be overridden by running p2pool"
            print "with the '--allow-obsolete-bitcoind' command-line option.\n\n\n"
            raise deferral.RetrySilentlyException()
Ejemplo n.º 6
0
def check(dcrd, net):
    if not (yield net.PARENT.RPC_CHECK(dcrd)):
        print >>sys.stderr, "    Check failed! Make sure that you're connected to the right dcrd with --dcrd-rpc-port!"
        raise deferral.RetrySilentlyException()
    version_check_result = net.VERSION_CHECK((yield dcrd.rpc_getinfo())['version'])
    if version_check_result == True: version_check_result = None # deprecated
    if version_check_result == False: version_check_result = 'Coin daemon too old! Upgrade!' # deprecated
    if version_check_result is not None:
        print >>sys.stderr, '    ' + version_check_result
        raise deferral.RetrySilentlyException()
Ejemplo n.º 7
0
def submit_block_p2p(block, factory, net):
    if factory.conn.value is None:
        print >> sys.stderr, 'No axed connection when block submittal attempted! %s%064x' % (
            net.PARENT.BLOCK_EXPLORER_URL_PREFIX,
            axe_data.hash256(axe_data.block_header_type.pack(block['header'])))
        raise deferral.RetrySilentlyException()
    factory.conn.value.send_block(block=block)
Ejemplo n.º 8
0
def getwork(bitcoind, use_getblocktemplate=False):
    def go():
        if use_getblocktemplate:
            return bitcoind.rpc_getblocktemplate(
                dict(mode='template', rules=['segwit']))
        else:
            return bitcoind.rpc_getmemorypool()

    try:
        start = time.time()
        work = yield go()
        end = time.time()
    except jsonrpc.Error_for_code(-32601):  # Method not found
        use_getblocktemplate = not use_getblocktemplate
        try:
            start = time.time()
            work = yield go()
            end = time.time()
        except jsonrpc.Error_for_code(-32601):  # Method not found
            print >> sys.stderr, 'Error: Bitcoin version too old! Upgrade to v0.5 or newer!'
            raise deferral.RetrySilentlyException()
    packed_transactions = [
        x['data'].decode('hex') for x in work['transactions']
        if len(x.get('depends', [])) == 0
    ]
    if 'height' not in work:
        work['height'] = (yield bitcoind.rpc_getblock(
            work['previousblockhash']))['height'] + 1
    elif p2pool.DEBUG:
        assert work['height'] == (yield bitcoind.rpc_getblock(
            work['previousblockhash']))['height'] + 1
    defer.returnValue(
        dict(
            version=work['version'],
            previous_block=int(work['previousblockhash'], 16),
            transactions=map(bitcoin_data.tx_type.unpack, packed_transactions),
            transaction_hashes=map(bitcoin_data.hash256, packed_transactions),
            transaction_fees=[
                x.get('fee', None) if isinstance(x, dict) else None
                for x in work['transactions']
            ],
            subsidy=work['coinbasevalue'],
            devreward_value=work['coinbasedevreward']['value'],
            devreward_scriptpubkey=work['coinbasedevreward']['scriptpubkey'],
            time=work['time'] if 'time' in work else work['curtime'],
            bits=bitcoin_data.FloatingIntegerType().unpack(
                work['bits'].decode('hex')[::-1]) if isinstance(
                    work['bits'],
                    (str,
                     unicode)) else bitcoin_data.FloatingInteger(work['bits']),
            coinbaseflags=work['coinbaseflags'].decode('hex')
            if 'coinbaseflags' in work else ''.join(
                x.decode('hex') for x in work['coinbaseaux'].itervalues())
            if 'coinbaseaux' in work else '',
            height=work['height'],
            rules=work.get('rules', []),
            last_update=time.time(),
            use_getblocktemplate=use_getblocktemplate,
            latency=end - start,
        ))
Ejemplo n.º 9
0
def checkwallet(dcrdwallet, net):
    print('wallet_check')
    wallet_dcrd_server_check_result = (
        yield dcrdwallet.rpc_walletinfo())['daemonconnected']
    if wallet_dcrd_server_check_result == False:
        print >> sys.stderr, '    ' + wallet_dcrd_server_check_result
        raise deferral.RetrySilentlyException()
Ejemplo n.º 10
0
 def height_cacher(block_hash):
     try:
         x = yield starwelsd.rpc_getblock('%x' % (block_hash,))
     except jsonrpc.Error_for_code(-5): # Block not found
         if not p2pool.DEBUG:
             raise deferral.RetrySilentlyException()
         else:
             raise
     defer.returnValue(x['blockcount'] if 'blockcount' in x else x['height'])
Ejemplo n.º 11
0
 def height_cacher(block_hash):
     if not block_hash in cached_heights:
         try:
             x = yield bitcoind.rpc_getblockheader('%x' % (block_hash,))
         except jsonrpc.Error_for_code(-5): # Block not found
             if not p2pool.DEBUG:
                 raise deferral.RetrySilentlyException()
             else:
                 raise
         cached_heights[block_hash] = x['blockcount'] if 'blockcount' in x else x['height']
     defer.returnValue(cached_heights[block_hash])
Ejemplo n.º 12
0
def check(bitcoind, net):
    if not (yield net.PARENT.RPC_CHECK(bitcoind)):
        print >> sys.stderr, "    Check failed! Make sure that you're connected to the right groestlcoind with --groestlcoind-rpc-port!"
        raise deferral.RetrySilentlyException()

    version_check_result = net.VERSION_CHECK(
        (yield bitcoind.rpc_getnetworkinfo())['version'])
    if version_check_result == True: version_check_result = None  # deprecated
    if version_check_result == False:
        version_check_result = 'Coin daemon too old! Upgrade!'  # deprecated
    if version_check_result is not None:
        print >> sys.stderr, '    ' + version_check_result
        raise deferral.RetrySilentlyException()

    try:
        softforks_supported = set(item for item in (
            yield bitcoind.rpc_getdeploymentinfo()).get('deployments', []))
    except jsonrpc.Error_for_code(-32601):  # Method not found
        softforks_supported = set()
    if getattr(net, 'SOFTFORKS_REQUIRED', set()) - softforks_supported:
        print 'Coin daemon too old! Upgrade!'
        raise deferral.RetrySilentlyException()
Ejemplo n.º 13
0
def submit_block_p2p(block, factory, net, bitcoind_work):
    if factory.conn.value is None:
        print >>sys.stderr, 'No bitcoind connection when block submittal attempted! %s%064x' % (net.PARENT.BLOCK_EXPLORER_URL_PREFIX, bitcoin_data.hash256(bitcoin_data.block_header_type.pack(block['header'])))
        raise deferral.RetrySilentlyException()

    segwit_rules = set(['!segwit', 'segwit'])
    segwit_activated = len(segwit_rules - set(bitcoind_work.value['rules'])) < len(segwit_rules)
    block_type = bitcoin_data.block_type if segwit_activated else bitcoin_data.stripped_block_type

    block = block_type.pack(block)
    block = block_type.unpack(block)

    factory.conn.value.send_block(block=block)
Ejemplo n.º 14
0
def getwork(bitcoind, use_getblocktemplate=False):
    def go():
        if use_getblocktemplate:
            return bitcoind.rpc_getblocktemplate(dict(mode='template'))
        else:
            return bitcoind.rpc_getmemorypool()
    try:
        start = time.time()
        work = yield go()
        end = time.time()
    except jsonrpc.Error_for_code(-32601): # Method not found
        use_getblocktemplate = not use_getblocktemplate
        try:
            start = time.time()
            work = yield go()
            end = time.time()
        except jsonrpc.Error_for_code(-32601): # Method not found
            print >>sys.stderr, 'Error: Bitcoin version too old! Upgrade to v0.5 or newer!'
            raise deferral.RetrySilentlyException()
    packed_transactions = [(x['data'] if isinstance(x, dict) else x).decode('hex') for x in work['transactions']]
    if 'height' not in work:
        work['height'] = (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
    elif p2pool.DEBUG:
        assert work['height'] == (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1

    fee_list = [x.get('fee', None) if isinstance(x, dict) else None for x in work['transactions']] # for FRC Parent transform unicode fees to int
    fee_helper = []
    for fee in fee_list:
        if isinstance(fee, unicode):
            float_fee = float(fee)
            int_fee = int(float_fee * 100000000)
            fee_helper.append(int_fee)
        else:
            fee_helper.append(fee)
    fee_list = fee_helper

    defer.returnValue(dict(
        version=work['version'],
        previous_block=int(work['previousblockhash'], 16),
        transactions=map(bitcoin_data.tx_type.unpack, packed_transactions),
        transaction_hashes=map(bitcoin_data.hash256, packed_transactions),
        transaction_fees=fee_list, # for FRC Parent +fee_list
        subsidy=work['coinbasevalue'],
        time=work['time'] if 'time' in work else work['curtime'],
        bits=bitcoin_data.FloatingIntegerType().unpack(work['bits'].decode('hex')[::-1]) if isinstance(work['bits'], (str, unicode)) else bitcoin_data.FloatingInteger(work['bits']),
        coinbaseflags=work['coinbaseflags'].decode('hex') if 'coinbaseflags' in work else ''.join(x.decode('hex') for x in work['coinbaseaux'].itervalues()) if 'coinbaseaux' in work else '',
        height=work['height'],
        last_update=time.time(),
        use_getblocktemplate=use_getblocktemplate,
        latency=end - start,
    ))
Ejemplo n.º 15
0
 def height_cacher(block_hash):
     try:
         block_hash_str = '%x' % (block_hash, )
         if len(block_hash_str) != 64:
             block_hash_str = '0' * (
                 64 - len(block_hash_str)) + block_hash_str
         x = yield bitcoind.rpc_getblock(block_hash_str)
     except jsonrpc.Error_for_code(-5):  # Block not found
         if not p2pool.DEBUG:
             raise deferral.RetrySilentlyException()
         else:
             raise
     defer.returnValue(x['blockcount'] if 'blockcount' in
                       x else x['height'])
Ejemplo n.º 16
0
def getwork(ezoncoind, net, use_getblocktemplate=False):
    def go():
        if use_getblocktemplate:
            return ezoncoind.rpc_getblocktemplate(dict(mode='template'))
        else:
            return ezoncoind.rpc_getmemorypool()
    try:
        start = time.time()
        work = yield go()
        end = time.time()
    except jsonrpc.Error_for_code(-32601): # Method not found
        use_getblocktemplate = not use_getblocktemplate
        try:
            start = time.time()
            work = yield go()
            end = time.time()
        except jsonrpc.Error_for_code(-32601): # Method not found
            print >>sys.stderr, 'Error: Ezoncoin version too old! Upgrade to v0.11.0.11 or newer!'
            raise deferral.RetrySilentlyException()
    packed_transactions = [(x['data'] if isinstance(x, dict) else x).decode('hex') for x in work['transactions']]
    packed_votes = [(x['data'] if isinstance(x, dict) else x).decode('hex') for x in work['votes']]
    if 'height' not in work:
        work['height'] = (yield ezoncoind.rpc_getblock(work['previousblockhash']))['height'] + 1
    elif p2pool.DEBUG:
        assert work['height'] == (yield ezoncoind.rpc_getblock(work['previousblockhash']))['height'] + 1
    defer.returnValue(dict(
        version=work['version'],
        previous_block=int(work['previousblockhash'], 16),
        transactions=map(ezoncoin_data.tx_type.unpack, packed_transactions),
        transaction_hashes=map(ezoncoin_data.hash256, packed_transactions),
        transaction_fees=[x.get('fee', None) if isinstance(x, dict) else None for x in work['transactions']],
        subsidy=work['coinbasevalue'],
        time=work['time'] if 'time' in work else work['curtime'],
        bits=ezoncoin_data.FloatingIntegerType().unpack(work['bits'].decode('hex')[::-1]) if isinstance(work['bits'], (str, unicode)) else ezoncoin_data.FloatingInteger(work['bits']),
        coinbaseflags=work['coinbaseflags'].decode('hex') if 'coinbaseflags' in work else ''.join(x.decode('hex') for x in work['coinbaseaux'].itervalues()) if 'coinbaseaux' in work else '',
        height=work['height'],
        last_update=time.time(),
        use_getblocktemplate=use_getblocktemplate,
        latency=end - start,
        votes=map(ezoncoin_data.vote_type.unpack, packed_votes),
        payee=ezoncoin_data.address_to_pubkey_hash(work['payee'], net.PARENT) if (work['payee'] != '') else None,
        masternode_payments=work['masternode_payments'],
        payee_amount=work['payee_amount'] if (work['payee_amount'] != '') else work['coinbasevalue'] / 5,
    ))
Ejemplo n.º 17
0
def getwork(bitcoind, use_getblocktemplate=False, txidcache={}, feecache={}, feefifo=[], known_txs={}):
    def go():
        if use_getblocktemplate:
            return bitcoind.rpc_getblocktemplate(dict(mode='template', rules=['segwit']))
        else:
            return bitcoind.rpc_getmemorypool()
    try:
        start = time.time()
        work = yield go()
        end = time.time()
    except jsonrpc.Error_for_code(-32601): # Method not found
        use_getblocktemplate = not use_getblocktemplate
        try:
            start = time.time()
            work = yield go()
            end = time.time()
        except jsonrpc.Error_for_code(-32601): # Method not found
            print >>sys.stderr, 'Error: Bitcoin version too old! Upgrade to v0.5 or newer!'
            raise deferral.RetrySilentlyException()

    if not 'start' in txidcache: # we clear it every 30 min
        txidcache['start'] = time.time()

    t0 = time.time()
    unpacked_transactions = []
    txhashes = []
    cachehits = 0
    cachemisses = 0
    knownhits = 0
    knownmisses = 0
    for x in work['transactions']:
        fee = x['fee']
        x = x['data'] if isinstance(x, dict) else x
        packed = None
        if x in txidcache:
            cachehits += 1
            txid = (txidcache[x])
            txhashes.append(txid)
        else:
            cachemisses += 1
            packed = x.decode('hex')
            txid = bitcoin_data.hash256(packed)
            txidcache[x] = txid
            txhashes.append(txid)
        if txid in known_txs:
            knownhits += 1
            unpacked = known_txs[txid]
        else:
            knownmisses += 1
            if not packed:
                packed = x.decode('hex')
            unpacked = bitcoin_data.tx_type.unpack(packed)
        unpacked_transactions.append(unpacked)
        # The only place where we can get information on transaction fees is in GBT results, so we need to store those
        # for a while so we can spot shares that miscalculate the block reward
        if not txid in feecache:
            feecache[txid] = fee
            feefifo.append(txid)

    if time.time() - txidcache['start'] > 30*60.:
        keepers = {(x['data'] if isinstance(x, dict) else x):txid for x, txid in zip(work['transactions'], txhashes)}
        txidcache.clear()
        txidcache.update(keepers)
        # limit the fee cache to 100,000 entries, which should be about 10-20 MB
        fum = 100000
        while len(feefifo) > fum:
            del feecache[feefifo.pop(0)]
    packed_transactions = [x['data'].decode('hex') for x in work['transactions'] if len(x.get('depends', [])) == 0]
    if 'height' not in work:
        work['height'] = (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1
    elif p2pool.DEBUG:
        assert work['height'] == (yield bitcoind.rpc_getblock(work['previousblockhash']))['height'] + 1

    t1 = time.time()
    if p2pool.BENCH: print "%8.3f ms for helper.py:getwork(). Cache: %i hits %i misses, %i known_tx %i unknown %i cached" % ((t1 - t0)*1000., cachehits, cachemisses, knownhits, knownmisses, len(txidcache))
    defer.returnValue(dict(
        version=work['version'],
        previous_block=int(work['previousblockhash'], 16),
        transactions=unpacked_transactions,
        transaction_hashes=txhashes,
        transaction_fees=[x.get('fee', None) if isinstance(x, dict) else None for x in work['transactions']],
        subsidy=work['coinbasevalue'],
        time=work['time'] if 'time' in work else work['curtime'],
        bits=bitcoin_data.FloatingIntegerType().unpack(work['bits'].decode('hex')[::-1]) if isinstance(work['bits'], (str, unicode)) else bitcoin_data.FloatingInteger(work['bits']),
        coinbaseflags=work['coinbaseflags'].decode('hex') if 'coinbaseflags' in work else ''.join(x.decode('hex') for x in work['coinbaseaux'].itervalues()) if 'coinbaseaux' in work else '',
        height=work['height'],
        rules=work.get('rules', []),
        last_update=time.time(),
        use_getblocktemplate=use_getblocktemplate,
        latency=end - start,
    ))
Ejemplo n.º 18
0
def getwork(dcrd, use_getblocktemplate=True):
    def go():
        print 'Getting blocktemplate ...'
        if not use_getblocktemplate:
            raise Exception("getblocktemplate only")
        return dcrd.rpc_getblocktemplate(dict(mode='template'))
    try:
        start = time.time()
        work = yield go()
        end = time.time()
    except jsonrpc.Error_for_code(-32601): # Method not found
        print >>sys.stderr, 'Error: Decred version too old! Upgrade to v1.1.1 or newer!'
        raise deferral.RetrySilentlyException()

    #
    # work
    #
    work['currtime'] = time.time()

    #
    # Block Header
    #
    block_header = work['header']
    packed_header = block_header.decode('hex')
    block_header_record = decred_data.block_header_type.unpack(packed_header)
    work['version'] = block_header_record.version
    work['bits'] = block_header_record.bits
    work['height'] = block_header_record.height
    work['previousblockhash'] = "{0:x}".format(block_header_record.previous_block)
    if p2pool.DEBUG:
        assert work['height'] == (yield dcrd.rpc_getblock(work['previousblockhash']))['height'] + 1

    #
    # Transactions/STransactions
    #
    txs = []
    for regtx in work['transactions']:
        tx = regtx['data']
        hash = regtx['hash']
        txs.append({'tx': tx, 'hash': hash})
    stxs = []
    for staketx in work['stransactions']:
        stx = staketx['data']
        hash = staketx['hash']
        stxs.append({'tx': stx, 'hash': hash}) 
    
    transaction_records = []
    transaction_hashes = []
    for t in txs:
        ptx = t['tx'].decode('hex')
        ptx_hash = t['hash'].decode('hex')
        tx_full = decred_data.tx_type.unpack(ptx)
        tx_full_hash = pack.IntType(256, endianness='big').unpack(ptx_hash)         # sent in on getblocktemplate
        transaction_records.append(tx_full)
        transaction_hashes.append(tx_full_hash)
        #
        # TODO: Find out if we really need the prefix hashes at a later point in the logic flow
        #
        if p2pool.DEBUG:
            alldata = decred_data.tx_type.get_all(ptx)
            print(hex(tx_full_hash), 'tx_full_hash:')
            print(hex(alldata['tx_full_hash']), 'alldata.tx_full_hash')
            print(hex(alldata['prefix_hash']), 'alldata.prefix_hash')
            print(hex(alldata['witness_hash']), 'alldata.witness_hash')
            assert tx_full_hash == alldata['tx_full_hash']
            print
    
    stransaction_records = []
    stransaction_hashes = []
    for s in stxs:
        ptx = s['tx'].decode('hex')
        ptx_hash = s['hash'].decode('hex')
        tx_full = decred_data.tx_type.unpack(ptx)
        tx_full_hash = pack.IntType(256, endianness='big').unpack(ptx_hash)         # sent in on getblocktemplate
        stransaction_records.append(tx_full)
        stransaction_hashes.append(tx_full_hash)
    
    wd = dict(
        version=work['version'],
        previous_block=int(work['previousblockhash'], 16),
        transactions=transaction_records,
        transaction_hashes=transaction_hashes,
        stransactions = stransaction_records,
        stransaction_hashes=stransaction_hashes,
        transaction_fees=[x.get('fee', None) if isinstance(x, dict) else None for x in work['transactions']], # TODO: FixMe for trans + strans
        subsidy=work['coinbasevalue'],
        time=work['currtime'],
        bits=decred_data.FloatingInteger(work['bits']),
        coinbaseflags=''.join(x.decode('hex') for x in work['coinbaseaux'].itervalues()),
        height=work['height'],
        last_update=time.time(),
        use_getblocktemplate=use_getblocktemplate,
        latency=end - start,
    )
    defer.returnValue(wd)
Ejemplo n.º 19
0
def getwork(axed, net, use_getblocktemplate=True):
    def go():
        if use_getblocktemplate:
            return axed.rpc_getblocktemplate(dict(mode='template'))
        else:
            return axed.rpc_getmemorypool()

    try:
        start = time.time()
        work = yield go()
        end = time.time()
    except jsonrpc.Error_for_code(-32601):  # Method not found
        use_getblocktemplate = not use_getblocktemplate
        try:
            start = time.time()
            work = yield go()
            end = time.time()
        except jsonrpc.Error_for_code(-32601):  # Method not found
            print >> sys.stderr, 'Error: axe version too old! Upgrade to v0.11.2.17 or newer!'
            raise deferral.RetrySilentlyException()

    if work['transactions']:
        packed_transactions = [
            (x['data'] if isinstance(x, dict) else x).decode('hex')
            for x in work['transactions']
        ]
    else:
        packed_transactions = []
    if 'height' not in work:
        work['height'] = (yield axed.rpc_getblock(
            work['previousblockhash']))['height'] + 1
    elif p2pool.DEBUG:
        assert work['height'] == (yield axed.rpc_getblock(
            work['previousblockhash']))['height'] + 1

    # Axe Payments
    packed_payments = []
    payment_amount = 0
    if 'payee' in work['masternode']:
        g = {}
        g['payee'] = str(work['masternode']['payee'])
        g['amount'] = work['masternode']['amount']
        if g['amount'] > 0:
            payment_amount += g['amount']
            packed_payments.append(g)
    elif work['superblock']:
        for obj in work['superblock']:
            g = {}
            g['payee'] = str(obj['payee'])
            g['amount'] = obj['amount']
            if g['amount'] > 0:
                payment_amount += g['amount']
                packed_payments.append(g)

    defer.returnValue(
        dict(
            version=work['version'],
            previous_block=int(work['previousblockhash'], 16),
            transactions=map(axe_data.tx_type.unpack, packed_transactions),
            transaction_hashes=map(axe_data.hash256, packed_transactions),
            transaction_fees=[
                x.get('fee', None) if isinstance(x, dict) else None
                for x in work['transactions']
            ],
            subsidy=work['coinbasevalue'],
            time=work['time'] if 'time' in work else work['curtime'],
            bits=axe_data.FloatingIntegerType().unpack(
                work['bits'].decode('hex')[::-1]) if isinstance(
                    work['bits'],
                    (str,
                     unicode)) else axe_data.FloatingInteger(work['bits']),
            coinbaseflags=work['coinbaseflags'].decode('hex')
            if 'coinbaseflags' in work else ''.join(
                x.decode('hex') for x in work['coinbaseaux'].itervalues())
            if 'coinbaseaux' in work else '',
            height=work['height'],
            last_update=time.time(),
            use_getblocktemplate=use_getblocktemplate,
            latency=end - start,
            payment_amount=payment_amount,
            packed_payments=packed_payments,
        ))
Ejemplo n.º 20
0
def check(bitcoind, net):
    if not (yield net.PARENT.RPC_CHECK(bitcoind)):
        print >>sys.stderr, "    Check failed! Make sure that you're connected to the right bitcoind with --bitcoind-rpc-port!"
        raise deferral.RetrySilentlyException()
Ejemplo n.º 21
0
def check(bitcoind, net):
    if not net.VERSION_CHECK((yield bitcoind.rpc_getinfo())['version']):
        print >> sys.stderr, '    Coin daemon too old! Upgrade!'
        raise deferral.RetrySilentlyException()
Ejemplo n.º 22
0
def getwork(dcrd,
            use_getblocktemplate=False
            ):  # TODO: remove getblocktemplate completely
    def go():
        if use_getblocktemplate:
            # gf: TOSO: remove getblocktemplate - decred does not have it
            raise Exception("getblocktemplate - not supported")
            #<-gf:
#       return dcrd.rpc_getrawmempool(True)  # verbose - keyed on tx hash
        return dcrd.rpc_getrawmempool(
            False)  # non-verbose - just the txids - keyed on tx hash

    try:
        start = time.time()
        mpool = yield go()
        end = time.time()
    except jsonrpc.Error_for_code(-32601):  # Method not found
        print >> sys.stderr, 'Error: Decred version too old! Upgrade to v0.5 or newer!'
        raise deferral.RetrySilentlyException()

#     packed_transactions = [(x['data'] if isinstance(x, dict) else x).decode('hex') for x in work['transactions']]
#     if 'height' not in work:
#         work['height'] = (yield dcrd.rpc_getblock(work['previousblockhash']))['height'] + 1
#     elif p2pool.DEBUG:
#         assert work['height'] == (yield dcrd.rpc_getblock(work['previousblockhash']))['height'] + 1
#     defer.returnValue(dict(
#         version=work['version'],
#         previous_block=int(work['previousblockhash'], 16),
#         transactions=map(decred_data.tx_type.unpack, packed_transactions),
#         transaction_hashes=map(decred_data.hash256, packed_transactions),
#         transaction_fees=[x.get('fee', None) if isinstance(x, dict) else None for x in work['transactions']],
#         subsidy=work['coinbasevalue'],
#         time=work['time'] if 'time' in work else work['curtime'],
#         bits=decred_data.FloatingIntegerType().unpack(work['bits'].decode('hex')[::-1]) if isinstance(work['bits'], (str, unicode)) else decred_data.FloatingInteger(work['bits']),
#         coinbaseflags=work['coinbaseflags'].decode('hex') if 'coinbaseflags' in work else ''.join(x.decode('hex') for x in work['coinbaseaux'].itervalues()) if 'coinbaseaux' in work else '',
#         height=work['height'],
#         last_update=time.time(),
#         use_getblocktemplate=use_getblocktemplate,
#         latency=end - start,
#     ))

#
# what we have is string transaction hashes in a list
#
    transaction_hashes = [x for x in mpool]

    #
    # for each txid above get raw and json data - this only works if dcrd is started with --txindex
    #
    transactions = []
    for txhash in transaction_hashes:
        rawtx = yield dcrd.rpc_getrawtransaction(
            txhash, 1)  # verbose - raw tx + txid + tx inpu/output data, etc.
        transactions.append(rawtx)

    curr_tip_height = (yield dcrd.rpc_getbestblock())['height']
    gw_previous_block = (yield dcrd.rpc_getblockhash(curr_tip_height))

    work = dict()

    defer.returnValue(work)