Пример #1
0
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)
Пример #2
0
def get_json_trans_from_rpc(block_number):
    # rpc_user and rpc_password are set in the bitcoin.conf file
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" % ('yuval', 'yuval1'))
    print('block ', block_number)
    block_hash = rpc_connection.batch_([["getblockhash", block_number]])
    print('block hash ', block_hash)
    block = rpc_connection.batch_([["getblock",i] for i in block_hash])
    print('reading raw transactions')
    trans_hex = rpc_connection.batch_([["getrawtransaction", tx] for tx in block[0]['tx']]) #list
    print('decoding raw transactions')
    json_trans = rpc_connection.batch_([["decoderawtransaction", tx_hex] for tx_hex in trans_hex])

    return [block[0]['height'],json_trans]
Пример #3
0
def update_bitcoin_other_info():
    global bitcoin_blockchain_info
    global bitcoin_recent_blocks
    global bitcoin_peers
    global bitcoin_network_info
    global bitcoin_mempool
    global bitcoin_wallet_info

    if bitcoin_blockchain_info == None:
        # We still havent gotten the important info... wait 1 minute and return
        time.sleep(60)
        return True

    try:
        rpc_user = get_bitcoin_rpc_username()
        rpc_pass = get_bitcoin_rpc_password()

        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                          (rpc_user, rpc_pass),
                                          timeout=60)

        # Get other less important info
        try:
            # Recent blocks
            commands = [["getblockhash", height]
                        for height in range(mynode_block_height -
                                            9, mynode_block_height + 1)]
            block_hashes = rpc_connection.batch_(commands)
            bitcoin_recent_blocks = rpc_connection.batch_(
                [["getblock", h] for h in block_hashes])

            # Get peers
            bitcoin_peers = rpc_connection.getpeerinfo()

            # Get network info
            bitcoin_network_info = rpc_connection.getnetworkinfo()

            # Get mempool
            bitcoin_mempool = rpc_connection.getmempoolinfo()

            # Get wallet info
            bitcoin_wallet_info = rpc_connection.getwalletinfo()
        except:
            pass

    except Exception as e:
        print "ERROR: In update_bitcoin_info - {}".format(str(e))
        return False

    return True
Пример #4
0
 def run(self, command, *args):
     try:
         rpc_connection = AuthServiceProxy(
             "http://%s:%s@%s:%s" % (self.rpc_user, self.rpc_password,
                                     self.rpc_host, self.rpc_port))
         try:
             cmd_args = self._build_args(command, *args)
             response = rpc_connection.batch_(cmd_args)
         except JSONRPCException as e:
             return RPCAdapterResponse(None, e.message, e.code)
         return RPCAdapterResponse(response[0])
     except Exception as e:
         message = 'Failed to run {} command'.format(command)
         self.log.error(message, e)
         raise RPCAdapterException(message)
Пример #5
0
def CallRPC(commands):
    global rpc_port
    global rrpc_user
    global rpc_password

    try:
        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:%s" %
                                          (rpc_user, rpc_password, rpc_port))
        print(f"connection: {rpc_connection}")
        result = rpc_connection.batch_(commands)
        print(f"Result type: {type(result)}")
    except JSONRPCException as json_exception:
        return "A JSON RPC Exception occured: " + str(json_exception)
    except Exception as general_exception:
        return "An Exception occured: " + str(general_exception)
    return result
Пример #6
0
    def handle(self, *args, **options):
        rpc_user = '******'
        rpc_password = '******'
        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:18443" %
                                          (rpc_user, rpc_password))
        results = rpc_connection.batch_([['listunspent']])
        unspents = results[0]
        for unspent in unspents:
            address = unspent["address"]
            amount = unspent["amount"]
            print('{}, {}'.format(unspent["address"], unspent["amount"]))
            try:
                order = Order.objects.get(address=address)
            except Order.DoesNotExist:
                continue

            if amount > order.amount or (order.amount -
                                         amount) / order.amount < 0.1:
                order.user.expire_date = add_months(order.user.expire_date,
                                                    order.month)
                order.user.save(update_fields=["expire_date"])
                order.delete()
Пример #7
0
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import logging

RPC_USER = '******'
RPC_PASSWORD = '******'
BITCOIN_SERVER = '127.0.0.1:8332'
AUTHSERV = 'http://' + RPC_USER + ':' + RPC_PASSWORD + '@' + BITCOIN_SERVER
print "AUTHSERV: %s" % (AUTHSERV)

# set logging to debug
logging.basicConfig()
logging.getLogger("BitcoinRPC").setLevel(logging.DEBUG)

# rpc_user and rpc_password are set in the bitcoin.conf file
rpc_connection = AuthServiceProxy(AUTHSERV)
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)
Пример #8
0
def update_bitcoin_other_info():
    global mynode_block_height
    global bitcoin_blockchain_info
    global bitcoin_recent_blocks
    global bitcoin_recent_blocks_last_cache_height
    global bitcoin_peers
    global bitcoin_network_info
    global bitcoin_mempool
    global bitcoin_wallets

    while bitcoin_blockchain_info == None:
        # Wait until we have gotten the important info...
        # Checking quickly helps the API get started faster
        time.sleep(1)

    try:
        rpc_user = get_bitcoin_rpc_username()
        rpc_pass = get_bitcoin_rpc_password()

        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:8332" %
                                          (rpc_user, rpc_pass),
                                          timeout=60)

        # Get other less important info
        try:
            # Recent blocks
            if mynode_block_height != bitcoin_recent_blocks_last_cache_height:
                commands = [["getblockhash", height]
                            for height in range(mynode_block_height -
                                                9, mynode_block_height + 1)]
                block_hashes = rpc_connection.batch_(commands)
                bitcoin_recent_blocks = rpc_connection.batch_(
                    [["getblock", h] for h in block_hashes])
                bitcoin_recent_blocks_last_cache_height = mynode_block_height

            # Get peers
            bitcoin_peers = rpc_connection.getpeerinfo()

            # Get network info
            bitcoin_network_info = rpc_connection.getnetworkinfo()

            # Get mempool
            bitcoin_mempool = rpc_connection.getmempoolinfo()

            # Get wallet info
            wallets = rpc_connection.listwallets()
            wallet_data = []
            for w in wallets:
                wallet_name = urllib.pathname2url(w)
                wallet_rpc_connection = AuthServiceProxy(
                    "http://%s:%[email protected]:8332/wallet/%s" %
                    (rpc_user, rpc_pass, wallet_name),
                    timeout=60)
                wallet_info = wallet_rpc_connection.getwalletinfo()
                wallet_data.append(wallet_info)
            bitcoin_wallets = wallet_data
        except:
            pass

    except Exception as e:
        print "ERROR: In update_bitcoin_info - {}".format(str(e))
        return False

    return True
Пример #9
0
def generate_valid_source_tx(
        s: protocol.State,
        con: AuthServiceProxy,
        max_tx: int
    ) -> None:
    # Transmit enough funds to addresses so that we won't need
    # to use coinbase transactions.
    # There are at most MAX many transactions in one step. Hence,
    # we need at most that many different addresses. (We can always
    # use the change addresses because our transactions have nearly
    # no costs)

    num_addr = max_tx // 10  # We want at most 50 advertisements to use the
    # same address
    s.source_tx = []

    start = con.getblockcount() + 1
    con.generate(num_addr + 101)
    top = con.getblockcount()

    interval = range(start, top - 100)
    block_hashes = con.batch_([["getblockhash", h] for h in interval])
    blocks = con.batch_([["getblock", ha, 2] for ha in block_hashes])
    del block_hashes
    txs = [block['tx'][0] for block in blocks]
    del blocks

    sent_txs = []
    i = 0
    value = -1
    txid = -1
    n = -1
    for tx in txs:
        for out in tx['vout']:
            if out['scriptPubKey']['type'] == 'pubkey':
                # The pubkey transactions are coinbase transactions because
                value = out['value']
                txid = tx['txid']
                n = out['n']
        if value == -1 or txid == -1 or n == -1:
            raise RuntimeError("No coinbase transaction found.")
        addr = con.getnewaddress()
        sent_value = float(value) / 2  # create two addresses per transaction
        raw_tx = con.createrawtransaction([{'txid': txid, 'vout': n}], {
            addr: sent_value})  # The - is for the fees
        funded_tx = con.fundrawtransaction(raw_tx)
        signed_tx = con.signrawtransactionwithwallet(funded_tx["hex"])
        if signed_tx["complete"] is False:
            raise RuntimeError(
                "bitcoind could not sign the transaction. (During "
                "Initialization)")
        txid = con.sendrawtransaction(signed_tx["hex"])
        sent_txs.append(txid)

        i += 1

        # Create a block each 100 transactions
        if i == 100:
            con.generate(1)
            i = 0

    con.generate(1)

    txs = con.batch_([['getrawtransaction', txid, 1] for txid in sent_txs])
    for tx in txs:
        for out in tx['vout']:
            vout = out['n']
            s.source_tx.append(opreturn.Transaction(tx['txid'], vout))
    c = 0
    for utxo in s.source_tx:
        if not protocol.is_valid_utxo(utxo):
            c += 1
    print("Found %d invalid utxos." % c)
Пример #10
0
conn = sqlite3.connect('txns.db')

# Database
c = conn.cursor()
c.execute ("DROP TABLE IF EXISTS TXNS;")
c.execute ("CREATE TABLE TXNS(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, HASH TEXT NOT NULL, SIZE INTEGER NOT NULL, OUTPUTS INTEGER NOT NULL, INPUTS INTEGER NOT NULL);")

best_block_hash = rpc_connection.getbestblockhash()
info = rpc_connection.getinfo()
chainheight= int(info["blocks"])
counter=chainheight-blockcount
print "Chain Height:",chainheight
print "Start Height:",counter
while (counter < chainheight):
    blockrange = range(counter,counter+1000)
    commands = [ [ "getblockhash", int(height)] for height in blockrange ]
    block_hashes = rpc_connection.batch_(commands)
    blocks = rpc_connection.batch_([ [ "getblock", h ] for h in block_hashes ])
    for block in blocks:
        txns = rpc_connection.batch_([ [ "getrawtransaction", tx, 1 ] for tx in block["tx"] ])
        for rawtx in txns:
                c.execute("INSERT INTO TXNS (HASH, SIZE, OUTPUTS, INPUTS) VALUES (\"" +str(rawtx["txid"]) + "\", " + str(rawtx["size"]) + "," + str(len(rawtx["vout"]))+ ","+ str(len(rawtx["vin"]))+");")
                print "Txn inserted",str(rawtx["txid"])
    if ((counter + 1000) > chainheight):
        counter = counter + (chainheight - counter)
    else:
        counter=counter+1000
    conn.commit()


conn.close()
Пример #11
0
import time
import threading
import sys
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException


# RAW DATA CONFIGURATION
rawdatafile="./rawdata.txt"
# Read the file
with open(rawdatafile) as f:
    txns = f.readlines()
# Strip the lines
txns = [x.strip() for x in txns]


rpc_user="******"
rpc_password="******"
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:28332"%(rpc_user, rpc_password))


# foreach tx in txns sendrawtransaction
commands = [ [ "sendrawtransaction", tx] for tx in txns ]

time0 = time.time()
result = rpc_connection.batch_(commands)
time1 = time.time() - time0

for res in result:
    print (str(res))

print (time1)
Пример #12
0
def pay(request, user_id, month):
    user = get_object_or_404(User, uuid=user_id)

    if month == 1:
        rmb = 15
        price = '1个月/15元'
    elif month == 3:
        rmb = 45
        price = '3个月/45元'
    elif month == 6:
        rmb = 90
        price = '半年/90元'
    elif month == 12:
        rmb = 180
        price = '一年/180元'
    else:
        raise Http404("Question does not exist")

    label = '小报童'
    message = '您的邮箱{},续订{}个月'.format(user.email, month)

    try:
        order = Order.objects.get(user=user, month=month)
        return render(
            request, 'pay.html', {
                'user':
                user,
                'btc_address':
                order.address,
                'qr_message':
                "bitcoin:{}?amount={}&label={}&message={}".format(
                    order.address, order.amount, label, message),
                'new_expire_date':
                add_months(user.expire_date, month),
                'price':
                price
            })
    except Order.DoesNotExist:
        # create new order (user, month) -> (amount, address)
        contents = urllib.request.urlopen(
            "https://blockchain.info/tobtc?currency=CNY&value={}".format(
                rmb)).read()
        contents.decode("utf-8")
        amount = float(contents)

        rpc_user = '******'
        rpc_password = '******'
        rpc_connection = AuthServiceProxy("http://%s:%[email protected]:18443" %
                                          (rpc_user, rpc_password))
        addresses = rpc_connection.batch_([['getnewaddress']])
        address = addresses[0]

        order = Order(user=user, month=month, address=address, amount=amount)
        order.save()

        factory = qrcode.image.svg.SvgFillImage
        qr_message = "bitcoin:{}?amount={}&label={}&message={}".format(
            order.address, order.amount, label, message)
        img = qrcode.make(qr_message, image_factory=factory)

        path = STATIC_ROOT + 'payments/{}.svg'.format(order.address)

        if os.path.isfile(path):
            os.remove(path)
            for i in range(0, 10):
                time.sleep(.1)
                if not os.path.isfile(path):
                    break

            if os.path.isfile(path):
                raise Http404("Question does not exist")

        img.save(path)

        for i in range(0, 10):
            time.sleep(.1)
            if os.path.isfile(path):
                new_expire_date = add_months(user.expire_date, month)
                return render(
                    request, 'pay.html', {
                        'user': user,
                        'btc_address': order.address,
                        'qr_message': qr_message,
                        'new_expire_date': new_expire_date,
                        'price': price
                    })

    except:
        raise Http404('支付系统维护中,请耐心等待')

    raise Http404('支付系统维护中,请耐心等待')
Пример #13
0
class Process():

    BCH_TO_SAT_MULTIPLIER = 100000000

    def __init__(self, url='http://*****:*****@'
        #url += '{}:{}'.format(host, port)

        self.out = out

        self.api = API()
        if self.api.version.major != 0:
            raise ValueError('this version of the ORBIT API is not supported: {}'.format(self.orbit.version))

        self.rpc = AuthServiceProxy(url, timeout=480)
        self.tokens = TokenDB(auto_commit=False)

        self.info = None

    def close(self):
        self.tokens.close()
        #self.rpc.close()

    def refresh(self):
        prev = None
        if self.info is not None:
            prev = self.info['blocks']

        self.info = self.rpc.getblockchaininfo()
        if self.out: print('last BCH block sync: {}'.format(self.info['blocks']), file=self.out)

        self.last = self.tokens.get_last_block()
        if self.out: print('last ORBIT block sync: {}'.format(self.last), file=self.out)

        last = self.last if self.last else self.api.launched - 1
        if self.out: print('blocks to sync: {}'.format(self.info['blocks'] - last), file=self.out)

        if self.info['blocks'] == prev:
            return False
        else:
            return True

    def get_info(self):
        if self.out: print("Collecting node information...", file=self.out)

        if self.out: print(file=self.out)
        if self.out: print("    ORBIT launch block: {}".format(self.api.launched), file=self.out)

        if self.out: print(file=self.out)
        if self.out: print('BCH node', file=self.out)
        info = self.rpc.getblockchaininfo()

        known = info['headers']
        if self.out: print("    Last known block: {}".format(known), file=self.out)

        completed = info['blocks']
        if self.out: print("    Last completed block: {}".format(completed), file=self.out)

        diff = known - completed
        if self.out: print("    Blocks to complete: {}".format(diff), file=self.out)

        pruned = info['pruned']
        if self.out: print("    Pruned? {}".format(pruned), file=self.out)

        if pruned:
            prune = info['pruneheight']
            if self.out: print("    Pruned at block: {}".format(prune), file=self.out)

        if self.out: print(file=self.out)
        if self.out: print('ORBIT node database', file=self.out)

        last = self.tokens.get_last_block()
        if self.out: print('    Last block sync: {}'.format(last), file=self.out)

        if not last:
            last = self.api.launched - 1

        diff = completed - last
        if self.out: print('    Blocks to sync: {}'.format(diff), file=self.out)

    def _chunks(self, data, size):
        for i in range(0, len(data), size):
            yield data[i:i+size]

    def next(self):
        if not self.info:
            self.refresh()

        if self.last is None:
            cur = self.api.launched
        else:
            cur = self.last + 1

        if cur > self.info['blocks']:
            if self.out: print('No more blocks', file=self.out)
            return None

        if self.out: print('processing block number {}'.format(cur), file=self.out)

        # FIXME check confirmations?

        blockhash = self.rpc.getblockhash(cur)
        block = self.rpc.getblock(blockhash)

        txcount = len(block['tx'])
        if self.out: print('    {} transaction{}...'.format(txcount, '' if txcount == 1 else 's'), end='', flush=True, file=self.out)

        # break into batches of 1,000
        txs = []
        txcount = 0
        txhashes = self._chunks(block['tx'], 1000)

        for txbatch in txhashes:
            if self.info['pruned']:
                # requires a recent Bitcoin-ABC node that includes the patch for lookups by txhash and blockhash
                txs.extend(self.rpc.batch_([ [ "getrawtransaction", txhash, True, block['hash'] ] for txhash in txbatch ]))
            else:
                txs.extend(self.rpc.batch_([ [ "getrawtransaction", txhash, True ] for txhash in txbatch ]))

            txcount += len(txbatch)
            if self.out: print('{}...'.format(txcount), end='', flush=True, file=self.out)

        if self.out: print('validating...', file=self.out)
        blockrow = self.tokens.save_block(blockhash, cur)

        registrations = self.tokens.get_active_registrations_map(blockrow)

        for tx in txs:
            #if i % 5000 == 0:
            #    if self.out: print('{}...'.format(i), end='', flush=True, file=self.out)

            txrow = None
            payments = []

            for vout in tx['vout']:
                value = vout['value']
                asmhex = vout['scriptPubKey']['hex']

                if asmhex.startswith('6a'): # OP_RETURN
                    try:
                        # FIXME: proper pushdata op and length check
                        orbit = self.api.parse(bytearray.fromhex(asmhex[4:])) # we skip the next byte too (pushdata)

                    except ValueError as e:
                        if self.out: print("        VOID {}: {}".format(tx['txid'], e), file=self.out)

                    if orbit is not None:
                        if self.out: print("        ORBIT @ {}".format(tx['txid']), file=self.out)
                        if self.out: print("            Token Address: {}".format(orbit[0]), file=self.out)
                        if self.out: print("            {}".format(orbit[1]), file=self.out)

                        if txrow is None:
                            txrow = self.save_tx_row(tx, blockrow)

                        try:
                            self.op(orbit[0], orbit[1], txrow, blockrow, registrations)

                        except TokenError as e:
                            # note that we don't rollback the sql transaction; we might want to re-evaluate the data later
                            if self.out: print("         !--VOIDED: {}".format(e), file=self.out)

                elif value:
                    addresses = vout['scriptPubKey']['addresses']

                    # because payments occur before OP_RETURN, we hold them to process after the vout loop
                    payments.append([addresses, value])

            for payment in payments:
                addresses = payment[0]
                value = payment[1]

                for address in addresses:
                    if address in registrations:
                        if len(addresses) > 1:
                            raise ValueError('Not expecting multiple addresses for a transaction with value')

                        if txrow is None:
                            txrow = self.save_tx_row(tx, blockrow)

                        regs_for_token = registrations[address]
                        from_address = self.tokens.get_signer_address(txrow)
                        reg_rowid = regs_for_token[from_address]

                        self.tokens.registration_payment(txrow, blockrow, reg_rowid, value)

        self.tokens.process_advertisements(blockrow)

        orbit = self.tokens.hash(blockrow)
        if self.out: print('    -> {}'.format(orbit), file=self.out)

        self.tokens.set_last_block(cur)
        self.tokens.commit()
        self.last = cur

        return cur

    def save_tx_row(self, tx, blockrow):
        txrow = self.tokens.save_tx(tx['txid'], blockrow, tx['confirmations'])

        for txin in tx['vin']:
            self.tokens.save_txin(txin['txid'], txrow, txin['scriptSig']['hex'])

        for txout in tx['vout']:
            script = txout['scriptPubKey']
            try:
                addresses = ','.join(script['addresses'])
            except KeyError:
                addresses = None

            self.tokens.save_txout(txrow, int(txout['value'] * self.BCH_TO_SAT_MULTIPLIER),
                    script['type'], addresses, script['hex'])

        return txrow

    def op(self, address, op, txrow, blockrow, registrations):
        signer_address = self.tokens.get_signer_address(txrow)

        if not signer_address:
            raise ValueError("Unable to determine signer's address from transaction inputs")

        if op.admin() == True:
            if signer_address != address:
                raise TokenError("Operation requires admin but no proof of ownership for token address in transaction")

        elif op.admin() == False:
            if signer_address == address:
                raise TokenError("Operation may not be used by admin but transaction indicates proof of ownership for token address")

        if isinstance(op, allocation.Create):
            self.tokens.token_create(address, txrow, blockrow,
                    op.supply, op.decimals, op.symbol, op.name, op.main_uri, op.image_uri)

        elif isinstance(op, allocation.Transfer):
            self.tokens.token_transfer(address, txrow, blockrow,
                    signer_address, op.to, op.units)

        elif isinstance(op, advertisement.Advertise):
            self.tokens.token_advertise(address, txrow, blockrow,
                    op.exchange_rate, op.units_avail, op.units_min, op.units_max, op.block_begin, op.block_end,
                    op.block_deliver, op.preregister)

        elif isinstance(op, advertisement.Cancel):
            raise NotImplementedError()

        elif isinstance(op, advertisement.Register):
            rowid = self.tokens.token_register(address, txrow, blockrow, signer_address, op.units_max)

            if address in registrations:
                token_regs = registrations[address]
            else:
                token_regs = {}
                registrations[address] = token_regs

            if signer_address in token_regs:
                raise ValueError("Already have an active registration for this user and token")

            token_regs[signer_address] = rowid

        elif isinstance(op, advertisement.Unregister):
            rowid = self.tokens.token_unregister(address, txrow, blockrow, signer_address)

        else:
            raise ValueError("API version mismatch? Unsupported token operation: {}".format(type(op)))
Пример #14
0
    script_dir = os.path.dirname(__file__)
    blocks = []
    start_height = int(raw_input("Enter start height: "))
    end_height = int(raw_input("Enter end height: "))
    step = 10  #int(raw_input("Enter step size: "))

    #integer division is being performed
    #start_height = ((start_height / step) * step)
    if ((end_height % step) != 0):
        end_height = (((end_height / step) + 1) * step)

    init = start_height
    for i in range(start_height + step, (end_height + 1), step):
        commands = [["getblockhash", height] for height in range(init, i)]
        block_hashes = rpc_connection.batch_(commands)
        #see for http rest batch processing support

        for hsh in block_hashes:
            #print hsh
            block = get_block_with_hash(hsh)
            blocks.append(block)

        f = open('JSONFiles/data%i.json' % i, 'w')
        json.dump(blocks, f, indent=4)
        f.close()
        blocks = []
        print i
        init = i
        #assert isinstance(block, Block)
        '''block_list = BlockList(blocks)                           
Пример #15
0
def getBlockHeadersInRange(ctx, i, j):
    rpc_connection = AuthServiceProxy(getBitcoinClientURL(ctx))

    commands = [["getblockhash", height] for height in range(i, j)]
    block_hashes = rpc_connection.batch_(commands)
    return block_hashes
Пример #16
0
def get_data_from_block_range(rpc_connection: authproxy.AuthServiceProxy,
                              block_min: int, block_max: int, modulo: int,
                              fuzzyness: int) -> list:
    """ Returns all data found in OP_RETURN transactions in the block range
        [block_min, block_max] as list of hex strings.

    Parameters
    ----------
    rpc_connection : bitcoinrpc.authproxy.AuthServiceProxy
        The RPC connection to the bitcoind client

    block_min : int
        Lower block range bound (included)
    block_max : int
        Upper block range bound (included)
    modulo : int
        Consider only blocks that have b mod modulo = 0
    fuzzyness : int
        Also consider a small intervall around above condition

    Returns
    -------
    list
        A list of OpData tuples containing a hex string representing the data
        found and the block height it was found as well as the potential
        catena-like input and output
    """
    interval = [
        i for i in range(block_min, block_max + 1) if (i % modulo) <= fuzzyness
    ]
    block_hashes = rpc_connection.batch_([["getblockhash", h]
                                          for h in interval])
    blocks = rpc_connection.batch_([["getblock", ha] for ha in block_hashes])
    del block_hashes

    res = []
    for b in blocks:
        merkle = b['merkleroot']
        raw_txs = rpc_connection.batch_([["getrawtransaction", t]
                                         for t in b["tx"]])
        txs = rpc_connection.batch_([["decoderawtransaction", r]
                                     for r in raw_txs])
        for t in txs:
            for out in t["vout"]:
                if out["scriptPubKey"]["type"] == "nulldata":
                    m_data = get_data_from_script_hex(
                        out["scriptPubKey"]["hex"])
                    m_height = b["height"]

                    # Catena continuation transaction is always FIRST input
                    first_tx = t['vin'][0]
                    m_input = _transaction_from_inputtx(first_tx)

                    # This is the OP_RETURN output, but we want the
                    # continuation output. Our transactions should always
                    # have exactly two outputs, so we can simply "switch"
                    vout = 1 if out["n"] == 0 else 0
                    m_output = Transaction(t['txid'], vout)
                    op_data = OpData(m_data, m_height, m_input, m_output,
                                     merkle)
                    res.append(op_data)

    return res
Пример #17
0
import binascii, leveldb
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

rpc_user = '******'
rpc_password = '******'

rpc = AuthServiceProxy("http://%s:%[email protected]:8332" %
                       (rpc_user, rpc_password))

height = 0
block_hashes = []
block_count = rpc.getblockcount()
while height < block_count:
    block_hashes.extend(
        rpc.batch_(
            [["getblockhash", height]
             for height in range(height, min([height + 10000, block_count]))]))
    height += 10000
print(len(block_hashes))

block_hashes = block_hashes[::-1]

f = open("bloomfilters.bin", "wb")

db = leveldb.LevelDB('./db')
block_counter = 0
while len(block_hashes) > 0:
    print(block_counter)
    batch_hashes = [
        block_hashes.pop() for x in range(min([100, len(block_hashes)]))
    ]
Пример #18
0
rpc_port = '8334'
if len(sys.argv) > 1:
    rpc_port = sys.argv[1]
if len(sys.argv) > 2:
    rpc_user = sys.argv[2]
if len(sys.argv) > 3:
    rpc_password = sys.argv[3]

print("Connected to port %s" % (rpc_port))
while True:
    rpc_connection = AuthServiceProxy("http://%s:%[email protected]:%s" %
                                      (rpc_user, rpc_password, rpc_port))
    print("Getting Lotto")
    try:
        command = [["getluckyaddress"]]
        response = rpc_connection.batch_(command)[0]
        lucky_address = response['lucky_address']
        owned_address = response['owned_address']
        up_for_grabs = response['up_for_grabs']
        print(response)
        if (owned_address == 'true'
                and up_for_grabs == 'true') or len(lucky_address) == 0:
            print("Sending generate command")
            command = [['generatetoaddress', 1, lucky_address]]
            response = rpc_connection.batch_(command)[0]
            print(response)
    except (KeyboardInterrupt):
        break
    except:
        time.sleep(1)
Пример #19
0
def setting():
    p = 0
    print "我们将会收取收益的5%作为费用,同意请按P,不同意请按下其他任意键:"
    info = raw_input()
    if info == "p" or info == "P":
        print "正在设置中………"
        if sett == 0:
            if os.makedirs("C:/WWS/date/COINNODE") :
                print "文件夹创建失败!请联系制作者2637037990  "
                print "程序异常 EXIT001"
                print "程序已关闭"
                os._exit(0)
            else:
                while p == 0 :
                    print "请输入您的币种"
                    coinname = raw_input()
                    print "请确认您的币种叫做",coinname,"正确请输入Y"
                    info = raw_input()
                    print info
                    if info == "Y"or info == "y" :
                        f = open("C:/WWS/date/COINNODE/set.inf","w")
                        f.write("#THIS IS WWS PROGRAM SET TXT DO NOT BREAK IT!")
                        f.write("\n")
                        f.write("[coinname] = '")
                        f.write(coinname)
                        f.write("'\n")
                        p = 1
                    else:
                        p = 0
                while p == 1 :
                    print "请输入钱包JSON-RPC IP地址(不包括端口)例:127.0.0.1"
                    info = raw_input()
                    ip = info
                    print "请输入钱包JSON-RPC 端口 例:5201”
                    info = raw_input()
                    port = info
                    print "请输入钱包JSON-RPC 用户名 : WWS"
                    info = raw_input()
                    username = info
                    print "请输入钱包JSON-RPC 密码 : WWS@#$J!@TY#!Y@Ghgew"
                    info = raw_input()
                    password = info
                    f.write("[ip] = '")
                    f.write(ip)
                    f.write("'\n")
                    f.write("[port] = '")
                    f.write(port)
                    f.write("'\n")
                    f.write("[username] = '")
                    f.write(username)
                    f.write("'\n")
                    f.write("[password] = '")
                    f.write(password)
                    f.write("'\n")
                    print "正在测试连接"
                    rpc_connection = AuthServiceProxy("http://"+username+password+"@"+ip+":"+port)
                    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 ]
                    if block_times > -1 :
                        print"测试成功!!!!!!!!"
                        f.write("[ip] = '")
                        f.write(ip)
                        f.write("'\n")
                        f.write("[port] = '")
                        f.write(port)
                        f.write("'\n")
                        f.write("[username] = '")
                        f.write(username)
                        f.write("'\n")
                        f.write("[password] = '")
                        f.write(password)
                        f.write("'\n")
                        p = 2
                    else:
                        p = 1
                        print "对不起!测试失败,请重试!"
        else:
            print "正在读取配置文件中"
            f = open("C:/WWS/date/COINNODE/set.inf")
            z = 0
            k = 0
            read = ""
            while k == 0 :
              z = z + 1
              line = f.readline()
              if z == 1 :
                  if line != "#THIS IS WWS PROGRAM SET TXT DO NOT BREAK IT!\n":
                     k = 1
                     print "数据遭到破坏!!!"
              read = read + line
              print read
              
    else:
        print "正在关闭程序………"
        print "进程关闭"
        os._exit(0)
Пример #20
0
def getBlocksInRange(ctx, i, j):
    block_hashes = getBlockHeadersInRange(ctx, i, j)
    rpc_connection = AuthServiceProxy(getBitcoinClientURL(ctx))
    blocks = rpc_connection.batch_([["getblock", h] for h in block_hashes])
    return blocks
Пример #21
0
class DaemonBTC:
    def __init__(self, url, timeout=90):
        self.rpc = AuthServiceProxy(url, timeout=timeout)

    def get_block(self, i):
        block = self.rpc.getblockhash(i)
        block_data = self.rpc.getblock(block)
        block_data['transactions'] = len(block_data['tx'])
        # Elasticsearch struggles with these as integers
        #block_data['chainwork_int'] = int(block_data['chainwork'], 16)
        block_data['difficulty'] = int(block_data['difficulty'])
        del (block_data['tx'])

        # Figure out how many coins moved
        value = 0
        txs = self.get_block_transactions(i)

        # This is the data we need for value
        # txs[0]['vout'][0]['value']
        for tx in txs:
            for vout in tx['vout']:
                if vout['scriptPubKey']['type'] == 'nonstandard':
                    pass
                else:
                    value = value + vout['value']

        block_data['value'] = value

        return block_data

    def get_transaction(self, tx):
        rtx = self.rpc.getrawtransaction(tx)
        dtx = self.rpc.decoderawtransaction(rtx)

        return dtx

    def get_transactions(self, txs):
        rtx = self.rpc.batch_([["getrawtransaction", t] for t in txs])
        dtx = self.rpc.batch_([["decoderawtransaction", t] for t in rtx])

        return dtx

    def get_block_transactions(self, block):

        # The genesis block is special
        if block == 0:
            return []

        blockhash = self.rpc.getblockhash(block)
        block_data = self.rpc.getblock(blockhash)

        transactions = []

        rtx = self.rpc.batch_([["getrawtransaction", t]
                               for t in block_data['tx']])
        dtx = self.rpc.batch_([["decoderawtransaction", t] for t in rtx])

        for tx in dtx:
            tx['height'] = block_data['height']
            tx['block'] = block_data['hash']
            tx['time'] = block_data['time']

            # We can't use this data, let's get rid of it
            for i in tx['vin']:
                if 'scriptSig' in i:
                    del (i['scriptSig'])
            for i in tx['vout']:
                if 'hex' in i['scriptPubKey']:
                    del (i['scriptPubKey']['hex'])
                if 'asm' in i['scriptPubKey']:
                    del (i['scriptPubKey']['asm'])

            transactions.append(tx)

        return transactions

    def get_block_transactions_bulk(self, block):
        "Return an iterable object for bulk transactions"

        transactions = self.get_block_transactions(block)
        tx = Transactions()
        for i in transactions:
            tx.add_transaction(i)

        return tx

    def get_blocks_bulk(self, blocks):

        rbh = self.rpc.batch_([["getblockhash", t] for t in blocks])

        dbh = self.rpc.batch_([["get_block", t] for t in rbh])

        output = []
        for block_data in dbh:
            block_data['transactions'] = len(block_data['tx'])
            block_data['chainwork_int'] = int(block_data['chainwork'], 16)
            del (block_data['tx'])
            output.append(block_data)

        return output

    def get_max_block(self):
        return self.rpc.getblockcount()