Esempio n. 1
0
def main():
    global rpc
    APP_NAME = 'bch-interlinker'
    NEW_TIP_CHECK_INTERVAL_SECONDS = 5

    config_path = save_config_path(APP_NAME)
    cache_path = save_cache_path(APP_NAME)
    db_path = path.join(cache_path, 'db')
    config_file_path = path.join(config_path, 'config.ini')

    config = configparser.ConfigParser()
    config.read(config_file_path)

    rpc = AuthServiceProxy("http://%s:%s@%s:%s" %
            (config['daemon']['user'], config['daemon']['password'],
                config['daemon']['host'], config['daemon']['port']))

    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%d/%m/%y %H:%M:%S %Z')
    logger = logging.getLogger(APP_NAME)
    logger.setLevel(logging.DEBUG)

    tip_id = ''
    while True:
        possibly_new_tip_id = rpc.getbestblockhash()
        if possibly_new_tip_id == tip_id:
            sleep(NEW_TIP_CHECK_INTERVAL_SECONDS)
            continue
        tip_id = possibly_new_tip_id
        logger.info('new block "%s"', tip_id)
        with shelve.open(db_path) as db:
            new_interlink = interlink(tip_id, db)
        logger.debug('new interlink "%s"', new_interlink)
        logger.info('mtr hash "%s"', new_interlink.hash().hex())
        logger.info('velvet tx "%s"', send_velvet_tx(new_interlink.hash()))
Esempio n. 2
0
class BitcoinCLI:

    def __init__(self):
        self.rpc_connection = AuthServiceProxy(config.endpoint)

    def get_best_block_hash(self):
        return self.rpc_connection.getbestblockhash()

    def get_block_count(self):
        return self.rpc_connection.getblockcount()

    def get_best_block(self):
        return self.rpc_connection.getblock(self.rpc_connection.getbestblockhash())

    def get_block_hash(self, height):
        return self.rpc_connection.getblockhash(height)

    def get_block(self, hash):
        return self.rpc_connection.getblock(hash)
    def get_transaction(self, hash):
        return self.rpc_connection.gettransaction(hash)

    def get_txn_list_from_block(self, hash):
        block = self.get_block(hash)

        if 'tx' in block:
            return block['tx']
        else:
            raise KeyError('Block {0} has no attribute tx'.format(hash))

    def get_raw_transaction(self, tx_id):
        out = self.rpc_connection.getrawtransaction(tx_id, 1)
        return out
    def decoderawtransaction(self, tx_id):
        out = self.rpc_connection.decoderawtransaction(raw)
        return out

    def get_tx_outputs(self, tx_id):
        tx = self.rpc_connection.getrawtransaction(tx_id, 1)
        outputs = [float(i['value']) for i in tx['vout']]
        return outputs

    def get_tx_details(self, tx_id):
        tx = self.rpc_connection.getrawtransaction(tx_id, 1)
        outputs = [float(i['value']) for i in tx['vout']]
        return outputs
Esempio n. 3
0
def main():
    rpc_user = '******'
    rpc_password = '******'
    rpc = AuthServiceProxy(f'http://{rpc_user}:{rpc_password}@127.0.0.1:18332/')
    #rpc = AuthServiceProxy(f'http://{rpc_user}:{rpc_password}@172.17.0.2:18332/')
    print(rpc.getinfo())
    best_block_hash = rpc.getbestblockhash()
    print(rpc.getblock(best_block_hash))
    blhash = rpc.getblockhash(0) #blhashはブロックのhash文字列
    bl = rpc.getblock(blhash) #blはブロック情報
    print(bl)
    dummy_address = '2MudgRfNaaw96kqAWziZ5JGsPbo2pzQp7Jy'
    change_address = '2NAVrak22jX3DQyDqnoqdm5ZTak1RgXWPzo'

    filename = 'mark_token.btc.json'
    url='https://drive.google.com/file/d/1ZR6Q5sCM_acUpPy7s3d9GJH8I2Plh4FI/view?usp=sharing'

    with open(filename, 'rb') as f:
        data2 = f.read()
    hashdata=hashlib.sha256(data2).hexdigest()
    js={'file_hash':hashdata,'url':url}
    data=json.dumps(js).encode("UTF-8")


    while True:
        if len(data) >= 80:
            buffer = data[:80]
            data = data[80:]
        elif len(data) == 0:
            break
        else:
            buffer = data
            data = b''

        first_unspent = rpc.listunspent()[0]
        txid = first_unspent['txid']
        vout = first_unspent['vout']
        input_amount = first_unspent['amount']
        SATOSHI = Decimal("0.00000001")
        change_amount = input_amount - Decimal("0.005") - SATOSHI

        tx = rpc.createrawtransaction([{"txid": txid, "vout": vout}],[{change_address: change_amount}, {'data': hexlify(buffer).decode('utf-8')}, ])
        tx = rpc.signrawtransactionwithwallet(tx)['hex']
        rpc.sendrawtransaction(tx)

    block_hash = rpc.generatetoaddress(1, change_address)[0]
    block = rpc.getblock(block_hash)
    txs = block['tx'][1:]

    print(f'# of txs: {len(txs)}')
    pprint(txs)

    for tx_hash in txs:
        raw_tx = rpc.gettransaction(tx_hash)['hex']
        decoded_tx = rpc.decoderawtransaction(raw_tx)
        # pprint(decoded_tx)
        print(decoded_tx['vout'][1]['scriptPubKey']['asm'])
def main():
    # rpc_user and rpc_password are set in the bitcoin.conf file
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" % (rpc_user, rpc_password))
    best_block_hash = rpc_connection.getbestblockhash()
    print(rpc_connection.getblock(best_block_hash))

    # batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips:
    commands = [["getblockhash", height] for height in range(100)]
    block_hashes = rpc_connection.batch_(commands)
    blocks = rpc_connection.batch_([["getblock", h] for h in block_hashes])
    block_times = [block["time"] for block in blocks]
    print(block_times)
Esempio n. 5
0
    async def update_dashboard_network(self, message):
        rpc_connection_CRYPTO = 'http://{0}:{1}@{2}:{3}'.format(
            crypto_perams.CRYPTO_RPC_USER, crypto_perams.CRYPTO_RPC_PW,
            crypto_perams.CRYPTO_RPC_IP, crypto_perams.CRYPTO_RPC_PORT)
        wallet = AuthServiceProxy(rpc_connection_CRYPTO)

        getmininginfo_response = wallet.getmininginfo()

        embed = discord.Embed(title="Shib Stats",
                              color=discord.Color.from_rgb(193, 151, 79))

        #1440 blocksper day
        #7.2 mn reward

        #row 1
        embed.add_field(
            name="Version",
            value=str(wallet.getnetworkinfo()["subversion"]).replace("/", ""),
            inline=True)
        embed.add_field(name="Connections",
                        value=str(wallet.getconnectioncount()),
                        inline=True)
        embed.add_field(name="Block Count",
                        value=getmininginfo_response["blocks"],
                        inline=True)

        embed.add_field(name="Difficulty",
                        value=round(getmininginfo_response["difficulty"], 2),
                        inline=True)
        embed.add_field(name="Nethash",
                        value=calc_converted_nethash(
                            getmininginfo_response["networkhashps"]),
                        inline=True)
        best_hash = wallet.getbestblockhash()

        #print("best hash = "+best_hash)

        embed.add_field(name="Blockhash",
                        value=best_hash[:8] + "..." + best_hash[-8:],
                        inline=True)

        embed.timestamp = datetime.datetime.utcnow()
        embed.set_footer(text="Last updated")
        #row 2
        embed.set_author(name=self.bot.user.name,
                         url=crypto_perams.WALLET_LINK,
                         icon_url=self.bot.user.avatar_url)

        await message.edit(content="", embed=embed)
class BtcRpc(object):
    def __init__(self, uri):
        logger.debug("init")
        self.uri = uri
        self.rpc = AuthServiceProxy(uri,timeout=600)

        # wait for rpc to be ready
        last_exc = None
        for _ in xrange(30):
            try:
                logger.info("best block: %s"%self.rpc.getbestblockhash())
                #logger.info("block count: %s" % self.rpc.getblockcount())
                break
            except Exception, e:
                last_exc = e
            logger.info("trying to connect ...")
            time.sleep(2)
        if last_exc:
            raise last_exc
        logger.debug("connected.")
Esempio n. 7
0
def run_cheetah(prevheight, rpc_user, rpc_password, rpc_port, cpu):

    # rpc_user and rpc_password are set in the bitcoin.conf file
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:%d" %
                                      (rpc_user, rpc_password, rpc_port))

    best_block_hash = rpc_connection.getbestblockhash()
    bestblock = rpc_connection.getblock(best_block_hash)

    cur_epoch = int(time.time())
    bcstucktime = cur_epoch - bestblock['time']

    if bcstucktime < 0:
        print "Height {} block Time is ahead of current time {} seconds, possible miner cheating on timestamp, current {} GMT".format(
            bestblock['height'], bcstucktime, datetime.utcnow())
    mining_info = rpc_connection.getmininginfo()

    if (bcstucktime > 120):
        print "ASIC/GPU miners got stuck on NENG blockchain for {} seconds".format(
            bcstucktime)
        print "Cheetah running, block {}: {} {} GMT".format(
            bestblock['height'], bestblock['time'], datetime.utcnow())

        if not mining_info['generate']:
            print("Cheetah accelerates, NENG CPU Mining Started")
            rpc_connection.setgenerate(True, cpu)
        elif bestblock['height'] != prevheight:
            print("Cheetah jumps, NENG CPU Mining Restarted")
            rpc_connection.setgenerate(False)
            rpc_connection.setgenerate(True, cpu)
    else:
        if mining_info['generate']:
            print "block {}: {} {} GMT".format(bestblock['height'],
                                               bestblock['time'],
                                               datetime.utcnow())
            print("Cheetah rests, NENG CPU Mining Stopped")
            rpc_connection.setgenerate(False)

    return bestblock['height']
Esempio n. 8
0
# user-config section
rpchost = ''
rpcuser = ''
rpcpass = ''

#main loop, catch exceptions
print ''
oldhash = ''
txiter=[]
txmemory=[]
primenumber = '030331ef01000000001976a914'
rpcpipe = AuthServiceProxy('http://' + rpcuser + ':' + rpcpass + '@' + rpchost + ':11000')
while True:
   try:
      #heartbeat     
      comms = rpcpipe.getbestblockhash()
      if comms not in oldhash:
         oldhash = comms
         print oldhash + ' ' + str(rpcpipe.getblockcount())
      time.sleep(5)
      #check for tx
      incmd = rpcpipe.listtransactions()
      for tx in incmd:
        if tx not in txmemory:
          if 'receive' in str(tx):
             fields = str(tx).split(',')
             for field in fields:
                 if 'txid' in field:
                    temptxid = field.split('u')[2].replace('{','').replace('}','').replace('\'','').strip()
                    bypass=False
                    if temptxid not in txiter:
Esempio n. 9
0
				print('                                      \\   /')
				print('                                       \\_/')
			elif len(str(int(round(sum(outset),-1)))) == 10:
				print('                                                 /\\')
				print('                                                /  \\')
				print('                                               /    \\')
				print('                                              /      \\')
				print('                                             /        \\')
				print('                                             '+str(int(round(sum(outset,-1)))))
				print('                                             \\        /')
				print('                                              \\      /')
				print('                                               \\    /')
				print('                                                \\  /')
				print('                                                 \\/')
			outset.clear()
	bestblockhash = rpc_doge.getbestblockhash()
	if bestblockhash not in cache:
		block = rpc_doge.getblock(bestblockhash)
		print('    _____________________ ')		
		print('   |                     |')		
		print('   |                     |')		
		print('   |                     |')		
		print('   |                     |')
		print('   |                     |')
		print('   |  wow such block     |')
		print('         '+str(len(block['tx'])))
		print('   |            many txs |')
		print('   |                     |')		
		print('   |                     |')		
		print('   |                     |')		
		print('   |                     |')
Esempio n. 10
0
class QtumBlockchain(BlockchainHandler):
    def __init__(self, qtum_rpc):
        self.qtum_rpc = qtum_rpc

        self.decode_hex = codecs.getdecoder("hex_codec")
        self.encode_hex = codecs.getencoder("hex_codec")

    @classmethod
    def from_http_provider(cls, http_provider):
        return cls(AuthServiceProxy(http_provider))

    def reload_http_provider(self, http_provider):
        self.qtum_rpc = AuthServiceProxy(http_provider)

    def get_block_count(self):
        return self.qtum_rpc.getblockcount()

    def get_balance(self):
        return self.qtum_rpc.getbalance()

    def get_last_block_hash(self):
        return self.qtum_rpc.getbestblockhash()

    def get_second_last_block_hash(self):
        return self.get_block_hash(self.get_block_count() - 1)

    def get_block_hash(self, height):
        return self.qtum_rpc.getblockhash(height)

    def get_block_id(self, height):
        block_hash = self.get_block_hash(height)

        l = sha256(self.decode_hex(block_hash)[0]).hexdigest()
        r = hex(height)

        return l[0:10] + r[2:].rjust(10, '0')

    def get_last_block_id(self):
        last_block_height = self.get_block_count()

        return self.get_block_id(last_block_height)

    def get_second_last_block_id(self):
        last_block_height = self.get_block_count() - 1

        return self.get_block_id(last_block_height)

    def get_accounts(self):
        unspent = self.qtum_rpc.listunspent()
        res = [tx['address'] for tx in unspent]

        return res

    def get_unspent(self):
        unspent = self.qtum_rpc.listunspent()
        res = {tx['address']: tx['amount'] for tx in unspent}

        return res

    def from_hex_address(self, address):
        return self.qtum_rpc.fromhexaddress(address)
Esempio n. 11
0
from bitcoinrpc.authproxy import AuthServiceProxy
import simplejson as json

for x in range(1, 4):
    access = AuthServiceProxy("http://*****:*****@172.17.0." + str(x + 1) +
                              ":18332")
    blockbesthash = access.getbestblockhash()
    blockbest = access.getblock(blockbesthash)
    #Affiche la hauteur du dernier block présent dans chaque noeuds
    print("node n:" + str(x) + " " + str(blockbest["height"]))

#Affichage des informations du dernier noeud
print json.dumps(access.getmininginfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getpeerinfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getnetworkinfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getblockchaininfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getrawmempool(), indent=4, separators=(',', ': '))
Esempio n. 12
0
        print access.getaddressesbyaccount(acct)
    except:
        print "\n---An error occurred---\n"

elif cmd == "getbalance":
    try:
        acct = raw_input("Enter an account (optional): ")
        mc = raw_input("Minimum confirmations (optional): ")
        try:
            print access.getbalance(acct, mc)
        except:
            print access.getbalance()
    except:
        print "\n---An error occurred---\n"
elif cmd == "getbestblockhash":
    print access.getbestblockhash()

elif cmd == "getblockbycount":
    height = raw_input("Height: ")
    print access.getblockbycount(height)

elif cmd == "getblockcount":
    print access.getblockcount()

elif cmd == "getblocknumber":
    print access.getblocknumber()

elif cmd == "getconnectioncount":
    try:
        print access.getconnectioncount()
    except:
Esempio n. 13
0
    while time > from_time:
        header = rpc.getblockheader(block_hash)
        time = datetime.utcfromtimestamp(header['time'])
        headers[time] = header
        block_hash = header['previousblockhash']


def find(from_time, to_time, from_value, to_value):
    addresses = {}
    for time in sorted(headers):
        if from_time <= time <= to_time:
            header = headers[time]
            block_hash = header['hash']
            block = rpc.getblock(block_hash, 2)
            for tx in block['tx']:
                for vout in tx['vout']:
                    value = vout['value']
                    if from_value <= value <= to_value:
                        address = vout['scriptPubKey']['addresses'][0]
                        if address not in addresses:
                            addresses[address] = []
                        addresses[address].append((time, value))
    return addresses


fetch_headers(rpc.getbestblockhash(), datetime.fromisoformat("2021-05-01"))
result_1 = find(datetime.fromisoformat("2021-05-08"), datetime.fromisoformat("2021-05-09"), 74.99, 75.01)
print(result_1)
result_2 = find(datetime.fromisoformat("2021-05-11"), datetime.fromisoformat("2021-05-12"), 78.28, 78.30)
print(result_2)
Esempio n. 14
0
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import time


# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_connection = AuthServiceProxy("http://*****:*****@172.17.0.3:18332")
# best_block_hash = rpc_connection.getbestblockhash()
# print(rpc_connection.getblock(best_block_hash))
for x in range(5):
    start = time.time()
    #result = rpc_connection.generate(1)
    result = rpc_connection.getbestblockhash()    
    # result = rpc_connection.getblocktemplate()    
    end = time.time()
    print(rpc_connection.generate(1))
    print(end-start)
exit(1)
# batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips:
commands = [ [ "getblockhash", height] for height in range(100) ]
block_hashes = rpc_connection.batch_(commands)
blocks = rpc_connection.batch_([ [ "getblock", h ] for h in block_hashes ])
block_times = [ block["time"] for block in blocks ]
print(block_times)
Esempio n. 15
0
"""
  Transmit a raw bitcoin transaction using Fldigi
"""

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import pyfldigi

CALLSIGN = 'KBBL' # update this

fldigi = pyfldigi.Client()
fldigi.modem.id = 40 # try 40-45 for BPSK31-500

btc = AuthServiceProxy("http://%s:%[email protected]:18443"%('foo','bar')) 
btc.getbestblockhash() # check to make sure it's working
addr = btc.getnewaddress() # generate address 
txhash = btc.sendtoaddress(addr, 1) # send 1 bitcoin to new address
tx = btc.getrawtransaction(txhash) # get raw transaction
print(tx)
txQueue = """QST DE %s\n \
<SIZE %s>%s<EOT>\n\
DE %s K
""" % (CALLSIGN, len(tx), tx, CALLSIGN)
timeout = round(len(tx)/3)
fldigi.main.send(txQueue, block=True, timeout=timeout)
fldigi.main.rx()
Esempio n. 16
0
class BitcoindRPCWrapper(BlockchainDataWrapper):
    '''
    A connection manager for bitcoind's RPC interface

    All RPC configuration variables will be set using the following env vars:
        * BOLTZMANN_RPC_USERNAME
        * BOLTZMANN_RPC_PASSWORD
        * BOLTZMANN_RPC_HOST
        * BOLTZMANN_RPC_PORT
    '''

    GENESIS_BLOCK = { #rpc-style format
        'txid':    ('4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2'
                    '127b7afdeda33b'),
        'version':  1,
        'locktime': 0,
        'vin': [{
            "sequence":4294967295,
            'coinbase': ('04ffff001d0104455468652054696d65732030332f4a6'
                         '16e2f32303039204368616e63656c6c6f72206f6e2062'
                         '72696e6b206f66207365636f6e64206261696c6f75742'
                         '0666f722062616e6b73')
        }],
        'vout': [
            {
                'value': 50.00000000,
                'n': 0,
                'scriptPubKey': {
                    'asm': ('04678afdb0fe5548271967f1a67130b7105cd6a828'
                            'e03909a67962e0ea1f61deb649f6bc3f4cef38c4f3'
                            '5504e51ec112de5c384df7ba0b8d578a4c702b6bf1'
                            '1d5f OP_CHECKSIG'),
                    'hex': ('4104678afdb0fe5548271967f1a67130b7105cd6a8'
                            '28e03909a67962e0ea1f61deb649f6bc3f4cef38c4'
                            'f35504e51ec112de5c384df7ba0b8d578a4c702b6b'
                            'f11d5fac'),
                    'reqSigs': 1,
                    'type': 'pubkey',
                    'addresses': ['1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa']
                }
            }
        ]
    }

    def __init__(self):
        rpc = dict()
        rpc['username'] = _get_env('BOLTZMANN_RPC_USERNAME')
        rpc['password'] = _get_env('BOLTZMANN_RPC_PASSWORD')
        rpc['host'] = _get_env('BOLTZMANN_RPC_HOST')
        rpc['port'] = _get_env('BOLTZMANN_RPC_PORT')

        self._con = AuthServiceProxy(
            "http://{username}:{password}@{host}:{port}".format(**rpc))


    def _get_raw_tx(self, txid):
        """Returns the transaction in raw format."""
        if txid == ('4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7af'
                    'deda33b'):
            raise NoDataAvailableForGenesisBlockError()
        else:
            return self._con.getrawtransaction(txid)


    def _get_decoded_tx(self, txid):
        """Gets a human-readable string of the transaction in JSON format."""
        try:
            return self._con.getrawtransaction(txid, 1)
        except NoDataAvailableForGenesisBlockError:
            #bitcoind won't generate this, but here's what it would look like
            return self.GENESIS_BLOCK


    def _get_block_height(self, txid, rpc_tx=None):
        """Return the block height at which the transaction was mined.

        Args:
            txid (str)
            rpc_tx (Optional[dict]): The data for the specified transaction, if
                it has already been queried previously from the RPC interface.

        Raises: NoBlockHeightAvailableError: If no block height found.
        """
        best_block_hash = self._con.getbestblockhash()
        best_block = self._con.getblock(best_block_hash)
        best_block_height = best_block['height']

        if rpc_tx is None:
            rpc_tx = self._get_decoded_tx(txid)

        #ready for a fun hack? We can compute block height, but only if the
        #transaction in question has at least one unspent output.
        for idx, _ in enumerate(rpc_tx['vout']):
            #Find number of confirmations for this transaction
            txout = self._con.gettxout(txid, idx)
            if txout is not None:
                return best_block_height - txout['confirmations'] + 1

        warn("Could not find number of confirmations in any txo for {0}".format(
            txid))
        return -1

    def _get_output_address(self, prev_txid, output_index, prev_tx=None):
        """Get the address associated with the specified txo.

        Args:
            prev_txid (str): The id of the tx the output belongs to
            output_index (int): Index within the outputs corresponding to the
                output
            prev_tx (Optional[dict]): The RPC-style prev tx the output belongs
                to. If not specified, this will be fetched from the RPC
                interface.

        TODO: This does not properly handle multisig outputs that list multiple
        addresses per output.

        Raises: PrevOutAddressCannotBeDecodedError
        """
        if prev_tx is None:
            prev_tx = self._get_decoded_tx(prev_txid)

        if('vout' in prev_tx and len(prev_tx['vout']) > output_index and
           'scriptPubKey' in prev_tx['vout'][output_index]):
            if 'addresses' not in prev_tx['vout'][output_index]['scriptPubKey']:
                raise PrevOutAddressCannotBeDecodedError(
                    "Can't decode address for txo {0}:{1}".format(prev_txid,
                                                                  output_index))
            else:
                return ' '.join(prev_tx['vout'][output_index]['scriptPubKey']['addresses'])
        else:
            raise PrevOutAddressCannotBeDecodedError(
                ("Missing element for vout in get_output_address() with tx "
                 "id {0} and output index {1}").format(prev_txid, output_index))

    def _rpc_to_bci_input(self, rpc_input):
        """Convert RPC-style input to BCI-style input.

        Args:
            rpc_input (dict): The RPC-style representation of an input, found in
                a transaction's 'vin' array.

        Returns: dict: Representation of input, to be appended to a list
        attribute called 'inputs'. The input contains these fields:
            * 'prev_out' (dict)
                * 'tx_index' (None)
                * 'txid' (str): previous tx id
                * 'addr' (str)
                * 'n' (int): position of txo in prev tx
                * 'value' (int)
        """
        bci_input = dict()

        #do not create prev_out field if this input is part of a coinbase
        #  transaction. This is consistent with the BCI JSON format.
        if 'txid' in rpc_input:
            bci_input['prev_out'] = dict()
            bci_input['prev_out']['tx_index'] = None
            prev_txid = rpc_input['txid']
            prev_vout_num = rpc_input['vout'] #RPC field is ambiguously named :/
            bci_input['prev_out']['n'] = prev_vout_num

            prev_tx = self._get_decoded_tx(prev_txid)
            bci_input['prev_out']['addr'] = self._get_output_address(
                prev_txid, prev_vout_num, prev_tx)
            bci_input['prev_out']['script'] = (prev_tx['vout'][prev_vout_num]
                                               ['scriptPubKey']['hex'])
            float_val = prev_tx['vout'][prev_vout_num]['value']
            bci_input['prev_out']['value'] = _float_to_satoshi(float_val)
        return bci_input


    def get_tx(self, txid, testnet):
        """Get the `Transaction` object for specified hash.
        
        Testnet parameter isn't used.
        For now, we assume that a single bitcoind is running on the machine. 
        
        The `Transaction` constructors expects these fields for a dict:
            * 'block_height' (int)
            * 'time' (None)
            * 'hash' (str)
            * 'inputs' (List[dict]):
                * 'prev_out' (dict):
                    * 'n' (int)
                    * 'value' (int)
                    * 'addr' (str)
                    * 'tx_index' (None)
            * 'out' (List[dict]): same as 'prev_out'
        """
        rpc_style_tx = self._get_decoded_tx(txid)
        rpc_style_tx['block_height'] = self._get_block_height(txid, rpc_style_tx)
        rpc_style_tx['time'] = None
        rpc_style_tx['hash'] = rpc_style_tx['txid']

        rpc_style_tx['inputs'] = list()
        for txin in rpc_style_tx['vin']:
            inpt = self._rpc_to_bci_input(txin)
            rpc_style_tx['inputs'].append(inpt)

        rpc_style_tx['out'] = list()
        for txout in rpc_style_tx['vout']:
            outpt = _rpc_to_bci_output(txout)
            rpc_style_tx['out'].append(outpt)

        return Transaction(rpc_style_tx)
    thefile = open('address.txt', 'w')
    for i in addrlist:
        #                print( i )
        thefile.write("%s\n" % i)
    thefile.close()


if __name__ == '__main__':
    # your bitcoin daemon on your server running full-node
    rpc_user = "******"
    rpc_password = "******"
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                      (rpc_user, rpc_password),
                                      timeout=1200)

    best_block_hash = rpc_connection.getbestblockhash()
    blk = rpc_connection.getblock(best_block_hash)

    # dump current block count height

    print("getblockcount = %s" % rpc_connection.getblockcount())

    txlist = []
    alist = []

    for txid in blk['tx']:
        txlist.append(txid)
        al = addrlistVout(txid)
        alist.append(al)

# make list & remove duplicates in list
Esempio n. 18
0
from bitcoinrpc.authproxy import AuthServiceProxy
import simplejson as json

for x in range(1, 4):
    access = AuthServiceProxy("http://*****:*****@172.17.0."+str(x+1)+":18332")
    blockbesthash = access.getbestblockhash()
    blockbest = access.getblock(blockbesthash)
    #Affiche la hauteur du dernier block présent dans chaque noeuds
    print ("node n:"+str(x)+" "+str(blockbest["height"]))

#Affichage des informations du dernier noeud
print json.dumps(access.getmininginfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getpeerinfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getnetworkinfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getblockchaininfo(), indent=4, separators=(',', ': '))
print json.dumps(access.getrawmempool(), indent=4, separators=(',', ': '))