Ejemplo n.º 1
0
 def get_rpcconn(self):
     ''' returns a working AuthServiceProxy for the bitcoind '''
     url = self.render_url()
     rpc = AuthServiceProxy(url)
     rpc.getblockchaininfo()
     logging.debug("created bitcoind-url {} is working".format(url))
     return rpc
Ejemplo n.º 2
0
    def test(self):
        '''raises JunctionErrors if RPC-connection doesn't work'''
        # Test RPC connection works
        try:
            # FIXME: want shorter timeout ...
            rpc = AuthServiceProxy(self.uri, timeout=0.5)
            rpc.getblockchaininfo()
        except (ConnectionRefusedError, http.client.CannotSendRequest) as e:
            raise JunctionError("ConnectionRefusedError: check https://bitcoin.stackexchange.com/questions/74337/testnet-bitcoin-connection-refused-111")
        except JSONRPCException as e:
            if "Unauthorized" in str(e):
                raise JunctionError("Please double-check your credentials!")

        # Check node version requirements are met
        version = rpc.getnetworkinfo()['version']
        if int(version) < 180000:
            raise JunctionError("Update your Bitcoin node to at least version 0.18")

        # Check wallet enabled
        try:
            rpc.getwalletinfo()
        except JSONRPCException as e:
            if "Method not found" in str(e):
                raise JunctionError("Junction requires 'disablewallet=0' in your bitcoin.conf")

        # Can't detect any problems
        return None
Ejemplo n.º 3
0
def start_bitcoind(bitcoind_path):
    datadir = tempfile.mkdtemp()
    bitcoind_proc = subprocess.Popen([
        bitcoind_path, '-regtest', '-datadir=' + datadir, '-noprinttoconsole'
    ])

    def cleanup_bitcoind():
        bitcoind_proc.kill()
        shutil.rmtree(datadir)

    atexit.register(cleanup_bitcoind)
    # Wait for cookie file to be created
    while not os.path.exists(datadir + '/regtest/.cookie'):
        time.sleep(0.5)
    # Read .cookie file to get user and pass
    with open(datadir + '/regtest/.cookie') as f:
        userpass = f.readline().lstrip().rstrip()
    rpc = AuthServiceProxy('http://{}@127.0.0.1:18443'.format(userpass))

    # Wait for bitcoind to be ready
    ready = False
    while not ready:
        try:
            rpc.getblockchaininfo()
            ready = True
        except JSONRPCException as e:
            time.sleep(0.5)
            pass

    # Make sure there are blocks and coins available
    rpc.generatetoaddress(101, rpc.getnewaddress())
    return (rpc, userpass)
Ejemplo n.º 4
0
    async def info(self, ctx):
        client = AuthServiceProxy(rpc_connection)
        user_id = str(ctx.author.id)

        if not user_db.check_user(user_id):
            embed = discord.Embed(title="**For first-use**", color=0x0043ff)
            embed.set_author(name=ctx.author.display_name,
                             icon_url=ctx.author.avatar_url_as(format='png',
                                                               size=256))
            embed.add_field(name="First of all, please type `//help`",
                            value="Welcome to CPUchain tipbot !")
            embed.set_thumbnail(
                url=self.bot.user.avatar_url_as(format='png', size=1024))
            embed.set_footer(text="CPUchain tipbot {0} [Owner: {1}]".format(
                config.VERSION, self.bot.get_user(config.OWNER_ID)),
                             icon_url=self.bot.user.avatar_url_as(format='png',
                                                                  size=256))

            await ctx.channel.send(embed=embed)
        else:
            pass

            block = client.getblockchaininfo()['blocks']
            hash_rate = round(client.getnetworkhashps() / 1000, 4)
            difficulty = client.getblockchaininfo()['difficulty']
            connection = client.getnetworkinfo()['connections']
            client_version = client.getnetworkinfo()['subversion']
            blockchain_size = round(
                client.getblockchaininfo()['size_on_disk'] / 1000000000, 3)

            embed = discord.Embed(title="**CPUchain info**", color=0x0043ff)
            embed.set_author(name=ctx.author.display_name,
                             icon_url=ctx.author.avatar_url_as(format='png',
                                                               size=256))
            embed.add_field(name="__Current block height__",
                            value="`{0}`".format(block),
                            inline=True)
            embed.add_field(name="__Network hash rate__",
                            value="`{0} KH/s`".format(hash_rate),
                            inline=True)
            embed.add_field(name="__Difficulty__",
                            value="`{0}`".format(difficulty),
                            inline=True)
            embed.add_field(name="__Connection__",
                            value="`{0}`".format(connection),
                            inline=True)
            embed.add_field(name="__Client Version__",
                            value="`{0}`".format(client_version),
                            inline=True)
            embed.add_field(name="__Block chain size__",
                            value="`About {0} GB`".format(blockchain_size),
                            inline=True)
            embed.set_footer(text="CPUchain tipbot {0} [Owner: {1}]".format(
                config.VERSION, self.bot.get_user(config.OWNER_ID)),
                             icon_url=self.bot.user.avatar_url_as(format='png',
                                                                  size=256))

            await ctx.channel.send(embed=embed)
Ejemplo n.º 5
0
    async def info(self, ctx):
        client = AuthServiceProxy(rpc_connection)
        user_id = str(ctx.author.id)
        user_name = ctx.author.name

        if not user_db.check_user(user_id):
            user_db.add_user(user_id, user_name)
            embed = discord.Embed(
                title="**How may I be of service?**",
                color=0x7152b6)
            embed.set_author(
                name=ctx.author.display_name,
                icon_url=ctx.author.avatar_url_as(format='png', size=256))
            embed.add_field(
                name="To see all my available commands type `!help`",
                value="If you have any issues please let one of the team know.")
            embed.set_thumbnail(url=self.bot.user.avatar_url_as(format='png', size=1024))
            embed.set_footer(text="TipBot v{0}".format(config.VERSION), icon_url=self.bot.user.avatar_url_as(format='png', size=256))

            await ctx.channel.send(embed=embed)
        else:
            pass

            block = client.getblockchaininfo()['blocks']
            hash_rate = round(client.getnetworkhashps() / 1000000000, 4)
            difficulty = round(client.getblockchaininfo()['difficulty'], 4)
            connection = client.getnetworkinfo()['connections']
            client_version = client.getnetworkinfo()['subversion']

            embed = discord.Embed(
                title="**Umbru Network Information**",
                color=0x7152b6)
            embed.set_author(
                name=ctx.author.display_name,
                icon_url=ctx.author.avatar_url_as(format='png', size=256))
            embed.add_field(
                name="**Current Block Height:**",
                value="`{0}`".format(block))
            embed.add_field(
                name="**Network Hash Rate:**",
                value="`{0} GH/s`".format(hash_rate))
            embed.add_field(
                name="**Difficulty:**",
                value="`{0}`".format(difficulty))
            embed.add_field(
                name="**Connections:**",
                value="`{0}`".format(connection))
            embed.add_field(
                name="**Wallet Version:**",
                value="`{0}`".format(client_version))
            embed.add_field(
                name="**Explorer:**",
                value="<https://explorer.umbru.io>")
            embed.set_footer(text="TipBot v{0}".format(config.VERSION), icon_url=self.bot.user.avatar_url_as(format='png', size=256))

            await ctx.channel.send(embed=embed)
Ejemplo n.º 6
0
def index():

    try:
        rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port))
        current_block_height = rpc_connect.getblockcount()
        onchain_peers = rpc_connect.getconnectioncount()
        onchain_balance = rpc_connect.getbalance() 
        bitcoin_version = (rpc_connect.getnetworkinfo()['subversion'])[1:-1].replace("Satoshi:","")
        sync_prog = str(round(rpc_connect.getblockchaininfo()['verificationprogress']*100, 2)) + "%"
        chain_type = rpc_connect.getblockchaininfo()['chain']
        if onchain_balance > 0 and chain_type == "main":
            onchain_balance = u"₿ " + str(onchain_balance)
        elif onchain_balance == 0:
            onchain_balance = u"₿ " + str(0)
        elif onchain_balance > 0 and chain_type == "test":
            onchain_balance = u"t₿ " + str(onchain_balance)          
        else:
            onchain_balance = u"t₿ " + str(0)

        if chain_type == "test":
            chaintype_ln = "testnet"
        else:
            chaintype_ln = "mainnet"
    except:
        current_block_height = onchain_peers = onchain_balance = bitcoin_version = sync_prog = chain_type = "Offline!"

    try: 
        os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA'
        with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f:
            macaroon_bytes = f.read()
            macaroon = codecs.encode(macaroon_bytes, 'hex')

        cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read()
        creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel('localhost:10009', creds)
        stub = lnrpc.LightningStub(channel)

        response = stub.GetInfo(ln.GetInfoRequest(), metadata=[('macaroon', macaroon)])
        satbalance = stub.ChannelBalance(ln.ChannelBalanceRequest(), metadata=[('macaroon', macaroon)])
        lightning_channels_act = response.num_active_channels
        lightning_peers = response.num_peers
        offchain_balance = u"ş " + str(format(satbalance.balance,','))
        lightning_version = response.version[:5]
        alias = response.alias
    except:

        lightning_channels_act = lightning_peers = offchain_balance = lightning_version = alias = "Offline!"


    return render_template('index.html', current_block_height=current_block_height,
         onchain_peers=onchain_peers, onchain_balance=onchain_balance, 
         bitcoin_version=bitcoin_version, sync_prog=sync_prog, chain_type=chain_type, lightning_channels_act=lightning_channels_act,
         lightning_peers=lightning_peers, offchain_balance=offchain_balance,
         lightning_version=lightning_version, alias=alias)
Ejemplo n.º 7
0
def rpcConnection():
    '''
    Tests RPC via Auth Service Proxy
    :return:
    '''
    rpc_connection = AuthServiceProxy("http://%s:%s@%s:%i/" % (rpcuser, rpcpassword, url, rpcport), timeout=120)
    # test it
    count = 0
    maxTries = 5
    while(count<maxTries):
        count += 1
        try:
            info = rpc_connection.getblockchaininfo()
            return rpc_connection
        except JSONRPCException as e:
            print("Authentication error " + str(e))
            print("Exiting program")
            sys.exit(1)
        except Exception as e:
            # apologies for bad exception catching
            print("Socket error when connecting to rpc")
            print(e)
            print("Waiting 5 seconds then trying again")
            time.sleep(5)
    print("Could not establish a connection")
    print("Exiting")
Ejemplo n.º 8
0
def connection():
    rpc_connection = AuthServiceProxy(
        "http://*****:*****@blockchain.oss.unist.hr:8332"
    )

    getnetworkinfo = rpc_connection.getnetworkinfo()
    getblockchaininfo = rpc_connection.getblockchaininfo()
    getnettotals = rpc_connection.getnettotals()
    getwalletinfo = rpc_connection.getwalletinfo()

    print("BLOCKCHAIN INFO")
    print("Tip mreže: %s" % (getblockchaininfo["chain"]))
    print("Verzija: %s" % (getnetworkinfo["subversion"]))
    print("Broj blokova: %s" % (getblockchaininfo["blocks"]))
    print("Veličina blockchaina na disku: %s" %
          ((getblockchaininfo["size_on_disk"])))
    print("Težina: %s" % (getblockchaininfo["difficulty"]))
    print("Primljeno: %s" % (getnettotals["totalbytesrecv"]))
    print("Poslano: %s" % (getnettotals["totalbytessent"]))

    print("\nWALLET INFO")
    print("Naziv novčanika: %s" % (getwalletinfo["walletname"]))
    print("Verzija novčanika: %s" % (getwalletinfo["walletversion"]))
    print("Stanje novčanika: %f" % (getwalletinfo["balance"]))
    print("Stanje novčanika (nepotvrđeno): %f " %
          (getwalletinfo["unconfirmed_balance"]))
    print("Broj transakcija: %s" % (getwalletinfo["txcount"]))
Ejemplo n.º 9
0
class BitcoinClient:
    rpc_connection: AuthServiceProxy = None

    def __init__(self, host: str, port: int, cookie_path: str):
        cookie = open(path.expanduser(cookie_path)).read().split(":")

        self.rpc_connection = AuthServiceProxy(
            "http://{user}:{password}@{host}:{port}".format(
                port=port,
                host=host,
                user=cookie[0],
                password=cookie[1],
            ))

    def get_blockchain_info(self):
        return self.rpc_connection.getblockchaininfo()

    def get_network_info(self):
        return self.rpc_connection.getnetworkinfo()

    def get_mempool_info(self):
        return self.rpc_connection.getmempoolinfo()

    def get_connection_count(self):
        return self.rpc_connection.getconnectioncount()
Ejemplo n.º 10
0
def bitcoind_wallet(bitcoind):
    # Use bitcoind to create a temporary wallet file, and then do cleanup after
    # - wallet will not have any keys, and is watch only
    import os, shutil

    fname = '/tmp/ckcc-test-wallet-%d' % os.getpid()

    disable_private_keys = True
    blank = True
    w = bitcoind.createwallet(fname, disable_private_keys, blank)

    assert w['name'] == fname

    # give them an object they can do API calls w/ rpcwallet filled-in
    cookie = get_cookie()
    url = 'http://' + cookie + '@' + URL + '/wallet/' + fname.replace(
        '/', '%2f')
    #print(url)
    conn = AuthServiceProxy(url)
    assert conn.getblockchaininfo()['chain'] == 'test'

    yield conn

    # cleanup
    bitcoind.unloadwallet(fname)
    assert fname.startswith('/tmp/ckcc-test-wallet')
    shutil.rmtree(fname)
Ejemplo n.º 11
0
class btcd(invoice):
    def __init__(self, dollar_value, currency, label, test=False):
        super().__init__(dollar_value, currency, label, test)
        print(self.__dict__)
        # self.__dict__ = invoice.__dict__.copy()

        from bitcoinrpc.authproxy import AuthServiceProxy

        connection_str = "http://{}:{}@{}:{}".format(config.username,
                                                     config.password,
                                                     config.host,
                                                     config.rpcport)
        print("Attempting to connect to {}.".format(connection_str))

        for i in range(config.connection_attempts):
            try:
                self.rpc = AuthServiceProxy(connection_str)

                if test:
                    info = self.rpc.getblockchaininfo()
                    print(info)

                print("Successfully contacted bitcoind.")
                break

            except Exception as e:
                print(e)
                time.sleep(config.pollrate)
                print("Attempting again... {}/{}...".format(
                    i + 1, config.connection_attempts))
        else:
            raise Exception("Could not connect to bitcoind. \
                Check your RPC / port tunneling settings and try again.")

    def check_payment(self):
        transactions = self.rpc.listtransactions()
        relevant_txs = [
            tx for tx in transactions if tx["address"] == self.address
        ]

        conf_paid = 0
        unconf_paid = 0
        for tx in relevant_txs:
            self.txid = tx["txid"]
            if tx["confirmations"] >= config.required_confirmations:
                conf_paid += tx["amount"]
            else:
                unconf_paid += tx["amount"]

        return conf_paid, unconf_paid

    def get_address(self):
        for i in range(config.connection_attempts):
            try:
                self.address = self.rpc.getnewaddress(self.label)
            except Exception as e:
                print(e)
                print("Attempting again... {}/{}...".format(
                    i + 1, config.connection_attempts))
        return
Ejemplo n.º 12
0
def bitcoind_d_wallet(bitcoind):
    # Use bitcoind to create a temporary DESCRIPTOR-based wallet file, and then do cleanup after
    # - wallet will not have any keys until a descriptor is added, and is not just watch-only
    import os, shutil

    fname = '/tmp/ckcc-test-desc-wallet-%d' % os.getpid()

    disable_private_keys = True
    blank = True
    password = None
    avoid_reuse = False
    descriptors = True
    w = bitcoind.createwallet(fname, disable_private_keys, blank,
                                            password, avoid_reuse, descriptors)

    assert w['name'] == fname

    # give them an object they can do API calls w/ rpcwallet filled-in
    cookie = get_cookie()
    url = 'http://' + cookie + '@' + URL + '/wallet/' + fname.replace('/', '%2f')
    #print(url)
    conn = AuthServiceProxy(url)
    assert conn.getblockchaininfo()['chain'] == 'test'

    yield conn

    # cleanup
    bitcoind.unloadwallet(fname)
    assert fname.startswith('/tmp/ckcc-test-desc-wallet')
    shutil.rmtree(fname)
Ejemplo n.º 13
0
class ChainData:

    RPC_USER = RPC_NODE["user"]
    RPC_PASSWORD = RPC_NODE["password"]
    RPC_SERVER = RPC_NODE["server"]
    RPC_PORT = RPC_NODE["port"]
    MIN_BLOCK = CHAIN["start_block"]
    MIN_CONFIRMS = CHAIN["confirms"]
    COIN = CHAIN["name"]

    def __init__(self):
        self.rpc_conn = AuthServiceProxy(
            "http://%s:%s@%s:%s" %
            (self.RPC_USER, self.RPC_PASSWORD, self.RPC_SERVER, self.RPC_PORT))

    def get_blocks(self):
        resp = self.rpc_conn.getblockchaininfo()
        return resp["blocks"]

    def get_headers(self):
        resp = self.rpc_conn.getblockchaininfo()
        return resp["headers"]

    def get_blockhash(self, block):
        resp = self.rpc_conn.getblockhash(block)
        return resp

    def _get_blocktransactions(self, block):
        blockhash = self.get_blockhash(block)
        resp = self.rpc_conn.getblock(blockhash, 2)
        return resp["tx"], blockhash

    def getblock_out_balances(self, block):
        txs, blockhash = self._get_blocktransactions(block)
        balances = []
        for tx in txs:
            for iout in tx['vout']:
                if iout.get("scriptPubKey") and iout.get("scriptPubKey").get(
                        "addresses"):
                    balances.append(
                        (iout["scriptPubKey"]["addresses"][0], iout["value"]))
                    if len(iout["scriptPubKey"]["addresses"]) > 1:
                        logger.error(
                            "More than one address detected! block %s, addresses: %s"
                            % (block, iout["scriptPubKey"]["addresses"]))
        return balances, blockhash
Ejemplo n.º 14
0
def main():
    brojac=0
    priceList=[]
    days=[]
    #spajanje na  server
    node_name="blockchain.oss.*****"
    port=*****
    rpc_user=*****
    rpc_password=******
    server =AuthServiceProxy("http://%s:%s@%s:%s"%(rpc_user,rpc_password,node_name,port))
     
    #podaci sa servera
    getinfo = server.getnetworkinfo()
    getblockinfo= server.getblockchaininfo() 
    getmininginfo= server.getmininginfo()
    

    print ("Host: %s , Port: %s"%(node_name,port))
    print ("Broj konekcija na server: ",getinfo["connections"])
    print ("Vrsta blockchaina: ",getblockinfo["chain"])
    print ("Visina bloka: ",getmininginfo["blocks"])
    print ("Zauzece diska: %.2f GB"%((getblockinfo["size_on_disk"]/(1024**3))))


 
  
    #zadaje se interval otkad dokad se dobije graf
    start=str(input("unesite pocetni datum u formatu yyyy-mm-dd: "))
    end=str(input("unesite krajnji datum u formatu yyyy-mm-dd: "))
    dan=str(input("unesite datum za koji zelite vrijednost u formatu yyyy-mm-dd: "))
    poveznica=("https://api.coindesk.com/v1/bpi/historical/close.json?")
    rez=(poveznica + 'start=' + start + '&'+ 'end='+end)
    #dan na koji se dobije vrijednost BTC
    datum=((poveznica + 'start=' + dan + '&'+ 'end='+end))
    specifican_dan=requests.get(datum).json()
    vrijednost=specifican_dan["bpi"][dan] 
    print ("Vrijednost BTC na datum",dan,"je ",vrijednost,"$")
   
    response= requests.get(rez).json()  
    date_time_obj = datetime.datetime.strptime(end, '%Y-%m-%d')
    kraj=date_time_obj.date()
    
    for i in range(1,(len(response["bpi"]))):
        dateInput=(kraj-timedelta(days=i))
        data=response["bpi"][str(dateInput)]
        priceList.append(data)
        days.append(str(dateInput))
        brojac+=1
    
    days.reverse()
    priceList.reverse()

    plt.plot(days,priceList)
    plt.xticks([days[0],days[round(brojac/5)],days[round(brojac/2)],days[round(brojac/1.2)],days[round(brojac-1)]])
    plt.ylabel("Cijena USD")
    plt.title("Cijena BTC kroz specificirani period")
    plt.grid(True)
    plt.show()
Ejemplo n.º 15
0
def sync():
   print("trying sync")
   try:
    rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,nodeip,rpc_port))
    blocks = rpc_connect.getblockcount()
    peers = rpc_connect.getconnectioncount()
    sync_prog = str(round(rpc_connect.getblockchaininfo()['verificationprogress']*100, 2)) + "%"
    return "👥 Peers: {}\n\n⏹ Block Height: {}\n\n🔄 Sync Progress: {}".format(peers, blocks, sync_prog)
   except:
    return "Something went wrong. Check your node is properly connected."
Ejemplo n.º 16
0
def bitcoind():
    # JSON-RPC connection to a bitcoind instance

    # see <https://github.com/jgarzik/python-bitcoinrpc>
    cookie = get_cookie()

    conn = AuthServiceProxy('http://' + cookie + '@' + URL)

    assert conn.getblockchaininfo()['chain'] == 'test'

    return conn
Ejemplo n.º 17
0
class ChainData:

    RPC_USER = RPC_NODE["user"]
    RPC_PASSWORD = RPC_NODE["password"]
    RPC_SERVER = RPC_NODE["server"]
    RPC_PORT = RPC_NODE["port"]

    def __init__(self):
        self.db1 = db.DataBase()
        self.rpc_conn = AuthServiceProxy(
            "http://%s:%s@%s:%s" %
            (self.RPC_USER, self.RPC_PASSWORD, self.RPC_SERVER, self.RPC_PORT))

    def get_blocks(self):
        resp = self.rpc_conn.getblockchaininfo()
        return resp["blocks"]

    def get_headers(self):
        resp = self.rpc_conn.getblockchaininfo()
        return resp["headers"]

    def get_blockhash(self, block):
        resp = self.rpc_conn.getblockhash(block)
        return resp

    def _get_blocktransactions(self, block):
        blockhash = self.get_blockhash(block)
        resp = self.rpc_conn.getblock(blockhash, 2)
        return resp["tx"], blockhash

    def getblock_out_addresses(self, block):
        txs, blockhash = self._get_blocktransactions(block)
        count = 0
        for tx in txs:
            for iout in tx['vout']:
                if iout.get("scriptPubKey") and iout.get("scriptPubKey").get(
                        "addresses"):
                    addresses = iout["scriptPubKey"]["addresses"]
                    for ad in addresses:
                        count += 1
                        self.db1.add_unique(ad)
Ejemplo n.º 18
0
class BtcRPC:
    def __init__(self):
        btcurl = "http://%s:%s@%s:%s" % (
            os.getenv('BITCOIN_RPC_USER'), os.getenv('BITCOIN_RPC_PASS'),
            os.getenv('BITCOIN_IP'), os.getenv('BITCOIN_RPC_PORT'))
        self.connection = AuthServiceProxy(btcurl)

    def connection_locked(self):
        try:
            response = self.connection.get_blockchain_info()
            return True
        except JSONRPCException:
            return False

    def get_blockchain_info(self):
        response = self.connection.getblockchaininfo()
        return response

    def get_sync_progress(self):
        response = self.connection.getblockchaininfo()
        return response["verificationprogress"] * 100
Ejemplo n.º 19
0
def getLastBlock(cfg):
    blk = 0
    while not done:
        try: # this tries to talk to bitcoind despite it being comatose
            rpc = AuthServiceProxy(cfg['rpc'], timeout=120)
            if blk == 0:
                blkinfo = rpc.getblockchaininfo()
                blk = blkinfo['blocks'] - 60
            blkhash = rpc.getblockhash(blk) # trailing by 60 to avoid reorg problems
            return blk,blkhash
        except Exception, e:
            log( 'Blkdat rpc ' + str(e) + ' trying again' )
            sleep(5) 
Ejemplo n.º 20
0
def init(options, configuration, plugin, **kwargs):
    global lightning_rpc, bitcoin_rpc, rpc_settings
    print(configuration)
    # setup lightning rpc
    lightning_dir, rpc_file = configuration['lightning-dir'], configuration['rpc-file']
    path = Path(f"{lightning_dir}/{rpc_file}")
    lightning_rpc = LightningRpc(str(path))

    # setup bitcoin rpc
    config = lightning_rpc.listconfigs()
    rpc_settings['user'] = config['bitcoin-rpcuser']
    rpc_settings['password'] = config['bitcoin-rpcpassword']
    rpc_settings['port'] = config['bitcoin-rpcport']
    rpc_settings['host'] = config['bitcoin-rpcconnect']
    network = config['network']

    template = "http://{user}:{password}@{host}:{port}"
    uri = template.format(**rpc_settings)
    bitcoin_rpc = AuthServiceProxy(uri)

    # check that it works
    bitcoin_rpc.getblockchaininfo()
Ejemplo n.º 21
0
def getpercentfin():
    try:
        # rpc_user and rpc_password are set in the bitcoin.conf file
        rpc_connection = AuthServiceProxy("http://%s:%s@%s:8332" %
                                          ("user", "user", "192.168.2.100"))
        best_block_hash = rpc_connection.getblockchaininfo()

        if round(best_block_hash["blocks"] / best_block_hash["headers"] * 100,
                 2) == 100:
            mineblock(rpc_connection.getblocktemplate())
    except JSONRPCException:
        print("You can't divide by zero, you're silly.")
    return
Ejemplo n.º 22
0
    async def info(self, ctx):
        client = AuthServiceProxy(
            f'http://{config.rpc_user}:{config.rpc_password}@{config.ip}:{config.rpc_port}'
        )
        user_id = str(ctx.author.id)

        block = client.getblockchaininfo()['blocks']
        hash_rate = round(client.getnetworkhashps() / 1000, 4)
        difficulty = client.getblockchaininfo()['difficulty']
        connection = client.getnetworkinfo()['connections']
        client_version = client.getnetworkinfo()['subversion']
        blockchain_size = round(
            client.getblockchaininfo()['size_on_disk'] / 1000000000, 3)

        embed = await utility.make_embed(ctx,
                                         self.bot,
                                         title="**Sugarchain info**",
                                         color=0x0043ff)
        embed.add_field(name="__Current block height__",
                        value="`{0}`".format(block),
                        inline=True)
        embed.add_field(name="__Network hash rate__",
                        value="`{0} KH/s`".format(hash_rate),
                        inline=True)
        embed.add_field(name="__Difficulty__",
                        value="`{0}`".format(difficulty),
                        inline=True)
        embed.add_field(name="__Connection__",
                        value="`{0}`".format(connection),
                        inline=True)
        embed.add_field(name="__Client Version__",
                        value="`{0}`".format(client_version),
                        inline=True)
        embed.add_field(name="__Block chain size__",
                        value="`About {0} GB`".format(blockchain_size),
                        inline=True)
        await ctx.channel.send(embed=embed)
Ejemplo n.º 23
0
def bitcoind():
    # JSON-RPC connection to a bitcoind instance

    try:
        cookie = open(os.path.expanduser(AUTHFILE), 'rt').read().strip()
    except FileNotFoundError:
        raise pytest.skip('no local bitcoind')

    # see <https://github.com/jgarzik/python-bitcoinrpc>

    conn = AuthServiceProxy('http://' + cookie + '@' + URL)

    assert conn.getblockchaininfo()['chain'] == 'test'

    return conn
Ejemplo n.º 24
0
def update_bitcoin_main_info():
    global bitcoin_block_height
    global mynode_block_height
    global bitcoin_blockchain_info

    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=120)

        # Basic Info
        bitcoin_blockchain_info = rpc_connection.getblockchaininfo()
        if bitcoin_blockchain_info != None:
            bitcoin_block_height = bitcoin_blockchain_info['headers']
            mynode_block_height = bitcoin_blockchain_info['blocks']

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

    return True
Ejemplo n.º 25
0
def rpcinfo_from_node():
    try:
        rpc_connection = AuthServiceProxy(
            "http://%s:%s@%s:%s" %
            (rpc_user, rpc_password, rpc_host, rpc_port),
            timeout=120)
        mining_info = rpc_connection.getmininginfo()
        mempool_info = rpc_connection.getmempoolinfo()
        blockchain_info = rpc_connection.getblockchaininfo()
        mempool_usage = mempool_info["usage"]
        mempool_minfee = mempool_info["mempoolminfee"]
        mempool_size = str(mempool_usage / (1024 * 1024))
        satfee = str(int(mempool_minfee * 100000000))
        block_height = str(blockchain_info["blocks"])
    except:
        mempool_usage = "?"
        mempool_minfee = "?"
        mempool_size = "?"
        satfee = "?"
        block_height = "?"
        scroll_message("RPC ERROR")
        scroll_message("CHECK VARIABLES")
    return mempool_usage, mempool_minfee, mempool_size, satfee, block_height
Ejemplo n.º 26
0
    async def on_message(self, message):
        split_msg = message.content.split(' ')

        if message.channel.id == self.reset_channel_id:
            self.time_last_block = datetime.datetime.now()
            return

        if split_msg[0] == '!info':
            msg = INFO_MESSAGE_TEMPLATE
            network_hashrate = 1
            pool_hashrate = 1

            async with aiohttp.get(
                    'https://garli.co.in/api/getnetworkhashps') as r:
                if r.status == 200:
                    data = await r.text()
                    network_hashrate = round(float(data) / 1e9, 2)
                    msg = msg.replace('[network_hashrate]',
                                      str(network_hashrate))

                else:
                    self.RequestError('Error retreiving network hashrate')
                    return

            access = AuthServiceProxy(JSON_RPC_ADDRESS)
            blockchain_info = access.getblockchaininfo()
            msg = msg.replace('[block_height]', str(blockchain_info['blocks']))
            msg = msg.replace('[difficulty]',
                              str(round(blockchain_info['difficulty'], 2)))

            async with aiohttp.get(FRESHGRLC_API_ADDRESS +
                                   '/poolstats/noheights') as r:
                if r.status == 200:
                    data = await r.json()
                    pool_hashrate = round(
                        float(data['averageHashrate']) / 1e9, 2)
                    msg = msg.replace('[pool_hashrate]', str(pool_hashrate))
                    msg = msg.replace('[workers]', str(data['workers']))

                else:
                    self.RequestError(
                        'Error retreiving pool pool hashrate and worker count')
                    return

            msg = msg.replace(
                '[percentage]',
                str(round(pool_hashrate / network_hashrate * 100, 2)))

            async with aiohttp.get(FRESHGRLC_API_ADDRESS + '/luck') as r:
                if r.status == 200:
                    data = await r.json()
                    luck_array = []
                    for blocks in data:
                        luck_array.append(blocks['luck'])
                    avg_luck = round(statistics.mean(luck_array) * 100, 2)
                    msg = msg.replace('[avg_luck]', str(avg_luck))

                else:
                    self.RequestError('Error retreiving pool pool luck')
                    return

            time_diff = datetime.datetime.now() - self.time_last_block
            time_since = str(time_diff)
            time_since = time_since[:time_since.find('.')]
            msg = msg.replace('[time_since]', time_since)

            embed = discord.Embed()
            embed.set_author(name='Fresh Garlic Blocks Info')
            embed.description = msg
            embed.color = discord.Color(0xffa517)

            await self.send_message(message.channel, embed=embed)
            return

        if split_msg[0] == '!cmc':
            coin_id = 'garlicoin'
            if len(split_msg) > 1:
                if bool(re.match('^[a-zA-Z0-9_-]+$', split_msg[1])):
                    coin_id = split_msg[1]
                else:
                    # No message if an invalid coin is specified.
                    return

            msg = CMC_MESSAGE_TEMPLATE
            async with aiohttp.get(
                    'https://api.coinmarketcap.com/v1/ticker/%s/' %
                    coin_id) as r:
                if r.status == 200:
                    data = await r.json()
                    coin = data[0]
                    for prop in coin:
                        msg = msg.replace('[%s]' % prop, str(coin[prop]))
                else:
                    raise self.RequestError('Error retreiving coin properties')
                    return

            coin_icon = await self.get_coin_icon(coin_id)
            if coin_icon is None:
                coin_icon = discord.Embed.Empty
            embed = discord.Embed()
            embed.set_author(name='%s | CoinMarketCap' % coin['name'],
                             url=self.coin_url(coin_id),
                             icon_url=coin_icon)
            embed.description = msg
            embed.color = discord.Color(0xffa517)

            await self.send_message(message.channel, embed=embed)
            return

        if split_msg[0] == '!myinfo':
            msg = WORKER_INFO_MESSAGE_TEMPLATE
            try:
                user = self.users[str(message.author)]
                msg = msg.replace('[address]', user['address'])

                async with aiohttp.get(
                        'https://garlicinsight.com/insight-grlc-api/addr/' +
                        user['address']) as r:
                    if r.status == 200:
                        data = await r.json()
                        balance = data['balance']
                        msg = msg.replace('[balance]', str(balance))

                    else:
                        self.RequestError('Error retreiving worker balance')
                        return

                async with aiohttp.get(FRESHGRLC_API_ADDRESS + '/workerinfo/' +
                                       user['address']) as r:
                    if r.status == 200:
                        data = await r.json()
                        expected_payout = data['nextpayout']['grlc']
                        worker_hashrate = data['hashrate']
                        worker_percentage = round(
                            data['nextpayout']['percentage'], 2)
                        if worker_hashrate is None:
                            worker_hashrate = 0

                        else:
                            worker_hashrate = round(
                                float(worker_hashrate) / 1e6, 2)

                        msg = msg.replace('[expected_payout]',
                                          str(expected_payout))
                        msg = msg.replace('[worker_hashrate]',
                                          str(worker_hashrate))
                        msg = msg.replace('[worker_percentage]',
                                          str(worker_percentage))

                    else:
                        self.RequestError(
                            'Error retreiving worker information')
                        return

            except KeyError:
                msg = ADDRESS_SET_ERROR_MESSAGE

            embed = discord.Embed()
            embed.set_author(name=message.author.display_name + "'s Info")
            embed.description = msg
            embed.color = discord.Color(0xffa517)

            await self.send_message(message.channel, embed=embed)
            return

        if split_msg[0] == '!register':
            address = split_msg[1]
            access = AuthServiceProxy(JSON_RPC_ADDRESS)
            if len(split_msg) > 1 and access.validateaddress(
                    address)['isvalid']:
                self.users[str(message.author)] = {'address': address}

                db_shelve = shelve.open('db')
                db_shelve['users'] = self.users
                db_shelve.close()

                embed = discord.Embed()
                embed.set_author(name=message.author.display_name +
                                 ' Registered')
                embed.description = 'You are now registered! Use`!myinfo` to see information about yourself!'
                embed.color = discord.Color(0xffa517)

                await self.send_message(message.channel, embed=embed)
                return
Ejemplo n.º 27
0
class UsdtWallet():
    USDT_BLOCK_NUM = 'http://www.tokenview.com:8088/coin/latest/USDT'
    USDT_TX_API = 'https://api.omniexplorer.info/v1/transaction/address'
    USDT_URL_BALANCE = 'https://api.omniexplorer.info/v1/address/addr/'

    def __init__(self, consul_client=None):
        if consul_client:
            self.init_consul(consul_client)

    def init_consul(self, app, consul_client):
        self.propertyid = 31
        # self.usdt_rpc_user = app.config["USDT_RPC_USER"]
        # self.usdt_rpc_password = app.config["USDT_RPC_PWD"]
        # self.usdt_passphrase = app.config.get('GETH_USDT_PASSPHRASE')
        # self.consul_client = consul_client
        # # self.wallet_url = self.consul_client.getRandomOneAvailableServiceIpPort(ConsulServiceName.USDTEREUM_CLI)
        # self.wallet_url = '47.52.131.71:7332'
        # print(self.wallet_url)
        # self.usdtcoin_cli = AuthServiceProxy(
        #     "http://%s:%s@" % (self.usdt_rpc_user, self.usdt_rpc_password) + self.wallet_url, timeout=10)
        # if not self.is_connected():
        #     logging.error('Connect USDT wallet node fial')
        self.usdtcoin_cli = AuthServiceProxy("http://%s:%[email protected]:7332" %
                                             ('xianda', 'ABQOqmPZ0tr95f5Z'))

    def is_connected(self):
        """获取钱包状态判读是否链接"""
        try:
            if self.usdtcoin_cli.getwalletinfo().get('walletversion'):
                return True
            return False
        except Exception as e:
            return False

    def is_syncing(self):
        """节点是否在同步中"""
        # 注意返回Flase表示节点同步完成
        info = self.usdtcoin_cli.getblockchaininfo()
        # print(info['blocks'], info['headers'])
        if info['blocks'] != info['headers']:
            return False
        else:
            return True

    def accountCreate(self, accountName):
        # 否则,创建账户,并返回账户地址
        address = self.usdtcoin_cli.getaccountaddress(accountName)
        privateKey = self.usdtcoin_cli.dumpprivkey(address)
        return privateKey, address

    # 檢驗賬戶是否有效
    def is_valid_address(self, address):
        if address is None or address == '':
            return False
        else:
            try:
                # print(self.usdtcoin_cli.validateaddress(address))
                return self.usdtcoin_cli.validateaddress(address).get(
                    'isvalid')
            except:
                return False

    # 獲取餘額
    def get_balance(self, address):
        """获取余额,默认最新区块"""
        try:
            balance = str(
                self.usdtcoin_cli.omni_getbalance(address,
                                                  self.propertyid)['balance'])
        except Exception as e:
            logging.error('USDT node get balance error:{}'.format(str(e)))
            raise Exception('USDT node get balance error')
        return Decimal(balance)

    def get_block_num(self):
        """获取最新区块数"""
        try:
            block_num = self.usdtcoin_cli.getblockcount()
        except Exception as e:
            logging.error('Get eth node block number error:{}'.format(str(e)))
            return
        return block_num

    def get_nonce(self, address):
        """获取账户nonce值"""
        try:
            # pending 获得最新已使用的nonce,对nonce进行加1
            nonce = len(
                self.usdtcoin_cli.omni_listpendingtransactions(address))
        except Exception as e:
            logging.error('USDT node get balance error:{}'.format(str(e)))
            raise Exception('USDT node get balance error')
        return nonce

    def get_mian_block_num(self):
        """获取公链上的最新区块数"""
        try:
            header = {
                'User-Agent':
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36',
            }
            ret = session_pool.get(self.USDT_BLOCK_NUM,
                                   headers=header,
                                   timeout=30).json()
            if ret is None:
                logging.error('Get usdt main chain block number error')
                return
            block_num = ret.get('data')
        except Exception as e:
            logging.error(
                'Get usdt main chain block number error:{}'.format(e))
            return
        return block_num  # int

    def get_minerFee(self, address):
        data = {'addr': address}
        try:
            balance = None
            rets = session_pool.post(self.USDT_URL_BALANCE,
                                     data=data,
                                     timeout=50).json().get('balance')
            if rets or len(rets) != 0:
                for ret in rets:
                    if ret.get('propertyinfo') and int(
                            ret.get('propertyinfo').get('propertyid')) == 0:
                        balance = ret.get('value')
        except Exception as e:
            logging.error(
                'Request USDT_TX_API error address:{},error:{},url:{}'.format(
                    address, str(e), self.USDT_TX_API))
            raise Exception('USDT node get balance error')
        return Decimal(balance) / 100000000

    def usdt_transaction_record(self,
                                address,
                                last_timestamp,
                                start_block=None,
                                end_block=None):
        """查询账户交易记录"""
        if start_block is None:
            start_block = 0
        if end_block is None:
            end_block = 99999999
        # 可能会有重复记录,使用此方法
        run_function = lambda x, y: x if y in x else x + [y]

        data = {'addr': address, 'page': 0}
        try:
            rets = session_pool.post(self.USDT_TX_API, data=data,
                                     timeout=50).json()
        except Exception as e:
            logging.error(
                'Request USDT_TX_API error address:{},error:{},url:{}'.format(
                    address, str(e), self.USDT_TX_API))
            rets = None

        new_records = []
        ret = rets.get('transactions')
        if ret is None:
            return new_records
        ret_page_num = int(rets.get('pages'))
        if ret_page_num == 1:
            # print(ret_page_num)
            self.query_records(address, ret, new_records, last_timestamp,
                               start_block, end_block)
            return (reduce(run_function, [
                [],
            ] + new_records))
        else:
            for i in range(0, ret_page_num):
                data = {'addr': address, 'page': i}
                try:
                    ret = session_pool.post(
                        self.USDT_TX_API, data=data,
                        timeout=50).json().get('transactions')
                except Exception as e:
                    logging.error(
                        'Request USDT_TX_API error address:{},error:{},url:{}'.
                        format(address, str(e), self.USDT_TX_API))
                    ret = None

                if ret is None:
                    return new_records
                self.query_records(address, ret, new_records, last_timestamp,
                                   start_block, end_block)
            return (reduce(run_function, [
                [],
            ] + new_records))

    def query_records(self, address, records, new_records, last_timestamp,
                      start_block, end_block):
        for record in records:
            propertyid = record.get('propertyid')
            valid = record.get('valid')
            block = record.get('block')
            if valid and int(propertyid) == 31 and int(start_block) <= int(
                    block) and int(block) <= int(end_block):
                to_address = record['referenceaddress']  # 是否为收款记录
                current_timestamp = int(record['blocktime'])  # 当前记录时间戳
                confirmations = int(record['confirmations'])  # 交易记录确认数
                record_hash = record['txid']
                amount = Decimal(record['amount'])
                if to_address.lower() != address.lower():
                    continue
                if int(last_timestamp) > int(current_timestamp):
                    continue
                if Order.hash_is_exist(record_hash):
                    continue
                if amount < Decimal('0.0000001'):
                    continue
                if confirmations < 2:
                    break
                else:
                    new_records.append(record)
            else:
                if records is None:
                    logging.error(
                        'Request USDT_TX_API fail address:{} ret:{}, url:{}'.
                        format(address, str(records), self.USDT_TX_API))
        return new_records

    def hash_get_detail(self, tx_hash):
        """hash获取交易细节,用于确认链外交易是否被确认"""
        # 交易是否被确认.status=1(被确认)
        is_confirm = False  # 是否确认
        is_success = False  # 如果已确认,交易是否成功
        msg = None  # 未被确认返回异常信息(一般超时),确认失败:失败的细节,确认成功:交易详情
        fee = None  # 确认成功交易的手续费
        try:
            ret = self.usdtcoin_cli.omni_gettransaction(tx_hash)  # 获取交易细节
        except Exception as e:
            msg = str(e)
            return is_confirm, is_success, msg, fee

        confirm = ret.get('confirmations')
        if confirm < 1:  # 确认交易失败
            msg = dict(fail_detail=str(ret))
            return is_confirm, is_success, msg, fee
        else:  # 确认交易成功
            is_confirm = True
            is_success = True
            fee = ret.get('fee')
            msg = dict(confirm=str(ret), tx_detail=str(ret))
            return is_confirm, is_success, msg, fee

    def payment(self, addrfrom, addrto, amount):
        """普通付款"""
        # 单位换算
        payload = {'from': addrfrom, 'to': addrto, 'value': str(amount)}
        try:
            # 钱包转账,返回交易哈希值
            tx_hash = self.usdtcoin_cli.omni_send(addrfrom, addrto,
                                                  self.propertyid, str(amount))
            return True, tx_hash
        except Exception as e:
            payload.update(dict(errormsg=str(e)))
            logging.error('usdt payment error:{}'.format(str(payload)))
            return False, str(e)

    def raw_transaction(self, minerfee_address, fromAddr, toAddre, value,
                        miner_minfee):
        # 查询USDT未使用的UTXO
        USDT_unspents = self.usdtcoin_cli.listunspent(1, 9999999, [fromAddr])
        if not USDT_unspents:
            return False, str('No USDT UTXO model available')
        USDT_unspent = USDT_unspents[0]
        # 查询BTC未使用的UTXO(矿工费)
        BTC_unspents = self.usdtcoin_cli.listunspent(1, 9999999,
                                                     [minerfee_address])
        if not BTC_unspents:
            return False, str('No BTC UTXO model available')
        BTC_unspent = BTC_unspents[0]
        # 所用值
        from_txid = USDT_unspent['txid']
        from_scriptPubKey = USDT_unspent['scriptPubKey']
        from_vout = USDT_unspent['vout']
        from_amount = USDT_unspent['amount']
        to_txid = BTC_unspent['txid']
        to_scriptPubKey = BTC_unspent['scriptPubKey']
        to_vout = BTC_unspent['vout']
        to_amount = BTC_unspent['amount']

        rawtransactionparams = [
            dict(txid=from_txid,
                 scriptPubKey=from_scriptPubKey,
                 vout=from_vout),
            dict(txid=to_txid, scriptPubKey=to_scriptPubKey, vout=to_vout),
        ]
        # 创建原生BTC交易获取哈希值
        RawTxChangeparams = [
            # 转出地址必须放在第一个,矿工费地址放在下面
            dict(txid=from_txid,
                 scriptPubKey=from_scriptPubKey,
                 vout=from_vout,
                 value=from_amount),
            dict(txid=to_txid,
                 scriptPubKey=to_scriptPubKey,
                 vout=to_vout,
                 value=to_amount),
        ]

        # 构造发送代币类型和代币数量数据
        payload = self.usdtcoin_cli.omni_createpayload_simplesend(
            self.propertyid, str(value))
        print('usdt交易', payload)

        # 构造交易基本数据
        data = {}
        btc_txid = self.usdtcoin_cli.createrawtransaction(
            rawtransactionparams, data)

        # 在交易上绑定代币数据
        rawtx = self.usdtcoin_cli.omni_createrawtx_opreturn(btc_txid, payload)
        print('usdt交易绑定到btc交易的哈希', rawtx)

        # 在交易上添加接收地址
        rawtx = self.usdtcoin_cli.omni_createrawtx_reference(rawtx, toAddre)
        print('添加接受地址', rawtx)

        # 在交易数据上指定矿工费用
        rawtx = self.usdtcoin_cli.omni_createrawtx_change(
            rawtx, RawTxChangeparams, minerfee_address, Decimal(miner_minfee))
        print('设置手续的哈希', rawtx)

        # 签名
        ret = self.usdtcoin_cli.signrawtransaction(rawtx)
        if not ret['complete']:
            return False, str('Incomplete signature')

        # 广播
        tx_hash = self.usdtcoin_cli.sendrawtransaction(ret['hex'])
        print('交易哈希', tx_hash)

        if tx_hash:
            return True, tx_hash
Ejemplo n.º 28
0
class BtcWallet():
    """btc钱包"""
    BTC_BLOCK_API = 'https://blockchain.info/'

    def __init__(self, app=None, consul_client=None):
        if app and consul_client:
            self.init_consul(app, consul_client)

    def init_consul(self, app, consul_client):
        try:
            rpc_user = app.config.get('CONFIG_BITCOIND_RPC_USER')
            rpc_pwd = app.config.get('CONFIG_BITCOIND_RPC_PASSWORD')
            wallet_passphrase = app.config.get('CONFIG_BITCOIND_WALLET_PASSWORD')
            self.ipport = consul_client.getRandomOneAvailableServiceIpPort(ConsulServiceName.BTC_CLI)
            # s = "http://%s:%s@" % (self.user, self.pwd) + self.ipport
            # print(s)

            self.bitcoin_cli = AuthServiceProxy(
                "http://%s:%s@" % (rpc_user, rpc_pwd) + self.ipport, timeout=10)
            print("Succeed to connect to the BTC node")

        except Exception as e:
            print(str(e))
            print("Failed to connect to the BTC node")

    # 是否连接BTC节点
    def is_connected(self):
        try:
            if self.bitcoin_cli.getwalletinfo().get('walletversion'):
                return True
            return False
        except Exception as e:
            print(str(e))
            print("Failed to connect to the BTC node")

    # 节点是否同步
    def is_sync(self):
        ret = self.bitcoin_cli.getblockchaininfo()
        if ret.get('blocks') != ret.get("headers"):
            return False
        else:
            return True

    # btc地址是否有效
    def is_valid_address(self, coin_address):
        if coin_address is None or coin_address == '':
            return False
        else:
            ret = self.bitcoin_cli.validateaddress(coin_address).get('isvalid')
            print('账户检查结果:', ret)
            return ret

            # return self.bitcoin_cli.validateaddress(coin_address).get('isvalid')

    # 获取账户余额, 默认经过6个区块确认
    def get_balance(self, coin_address):

        transaction_lists = self.bitcoin_cli.listunspent(1, 99999999, [coin_address])
        print(transaction_lists)
        current_amount = 0
        for transaction_list in transaction_lists:
            amount = transaction_list.get('amount')
            amount = float(amount)
            current_amount += amount
        return current_amount

    def get_balance_by_account(self, account):
        try:
            ret = self.bitcoin_cli.getbalance(account)
            return ret
        except Exception as e:
            logging.error('get balance error:{}'.format(str(e)))
            return None


    def estimate_fee(self):
        try:
            fee = self.bitcoin_cli.estimatefee(6)
            return fee
        except Exception as e:
            logging.error('get fee error:{}'.format(str(e)))
            return None

    def create_account(self, stellar_account):
        # private = random_key()
        # address = pubtoaddr(privtopub(private))
        # print(address, private)
        # return address, private
        address = self.bitcoin_cli.getnewaddress(stellar_account)
        private_key = self.bitcoin_cli.dumpprivkey(address)
        return address, private_key

    def get_block_num(self):
        """获取最新区块数"""
        try:
            block_num = self.bitcoin_cli.getblockcount()
            return block_num
        except Exception as e:
            logging.error('Get btc node block number error:{}'.format(str(e)))
            return None


    def get_chain_info(self):
        ret = self.bitcoin_cli.getblockchaininfo()
        return ret

    def get_block_info(self, block_num):
        """获取区块的详细信息"""
        param = "block-height/{}?format=json".format(block_num)
        api_url = self.BTC_BLOCK_API + param
        # print(api_url)

        blocks = requests.get(api_url, timeout=500).json()
        # print(type(blocks))
        return blocks

    # 链外转帐,普通交易
    def payment(self, btc_base_account, address_to, amount):
        try:
            txid = self.bitcoin_cli.sendfrom(btc_base_account, address_to, amount)
            return True, txid
        except Exception as e:
            logging.error('btc payment error:{}'.format(str(e)))
            return False, str(e)

    def hash_get_detail(self, tx_id):
        """
        Arguments:
        1. "txid" (string, required) The transaction id
        """
        # 根据txid获取确认链外交易信息
        ret = self.bitcoin_cli.gettransaction(tx_id)
        abandoned = ret.get("details")[0].get("abandoned")  # 获取abandon信息
        confirmation_num = ret.get('confirmations')  # 获取确认数

        # 如果确认数小于1,则未确认
        if confirmation_num < 1:
            msg = dict(confirm=str(ret))
            # msg = ret.get("details")[0]
            return False, False, msg, None
        # 如果确认数大于1,则确认
        else:
            msg = dict(confirm=str(ret))
            # msg = ret
            fee = abs(ret.get("fee"))
            if abandoned:
                return True, False, msg, None
            else:
                return True, True, msg, fee

    def raw_payment(self, address_from, address_to, collect_amount):
        inputs = []
        # 获取地址余额信息
        try:
            unspend_lists = self.bitcoin_cli.listunspent(1, 9999999, [address_from])
            for unspend_list in unspend_lists:
                # if unspend_list.get('amount') <= 0:
                #     continue
                # else:
                txid = unspend_list.get('txid')
                vout = unspend_list.get('vout')
                inputs.append({'txid': txid, 'vout': vout})

            outputs = {address_to: round(collect_amount, 8)}

            # 交易建立和签名时不用连接比特币网络,只有在执行交易时才需要将交易发送到网络
            # 创建裸交易
            transaction_hash = self.bitcoin_cli.createrawtransaction(inputs, outputs)

            # 使用私钥签名,获取16进制信息
            hex = self.bitcoin_cli.signrawtransaction(transaction_hash).get('hex')

            # 广播到p2p网络,返回交易哈希
            trading_hash = self.bitcoin_cli.sendrawtransaction(hex, False)

            return True, trading_hash, ''
        except Exception as e:
            print(e)
            return None, None, ''

    def btc_transaction_record(self, block_num):
        # 获取某一区块信息
        block_info = self.get_block_info(block_num)
        blocks = block_info.get('blocks')
        txs = blocks[0].get('tx')
        records = []
        for tx in txs:
            outs = tx.get('out')
            hash = tx.get('hash')
            inputs = tx.get('inputs')
            p_out = inputs[0].get('prev_out')
            if not p_out:
                continue
            else:
                addr_from = p_out.get('addr')
            for out in outs:
                re = []
                addr_to = out.get('addr')
                value = out.get('value') / (10 ** 8)
                # addr_to与User表中绑定的地址进行对比,如果有,则说明此address_to有冲币记录
                user = User.address_query_user('BTC', addr_to)
                if not user:
                    continue
                else:
                    re.append(addr_from)
                    re.append(addr_to)
                    re.append(value)
                    re.append(hash)
                    records.append(re)
        return records

    def get_accounts(self, addr):
        try:
            ad = self.bitcoin_cli.getaccount(addr)
            return ad
        except Exception as e:
            # logging.error('get btc_account error:{}'.format(str(e)))
            return None

    def get_address_byaccount(self, account):
        re = self.bitcoin_cli.getaddressesbyaccount(account)

        return re

    def test1(self):

        transaction_list = self.bitcoin_cli.listaccounts()
        # transaction_list = self.bitcoin_cli.getwalletinfo()
        print(transaction_list)
Ejemplo n.º 29
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=(',', ': '))
Ejemplo n.º 30
0
class BitcoinClient(object):
    """Bitcoin client class"""

    # Handler for Bitcoin connection
    connection = None

    network_info = None
    blockchain_info = None
    wallet_info = None

    def __init__(self):
        self.user = os.environ["BITCOIN_USER"]
        self.password = os.environ["BITCOIN_PASSWORD"]
        self.host = os.environ["BITCOIN_HOST"]
        self.port = int(os.environ["BITCOIN_PORT"])

        self.connection = AuthServiceProxy(
            "http://%s:%s@%s:%i" %
            (self.user, self.password, self.host, self.port))

    def info(self):
        # Use following links for reference:
        # https://chainquery.com/bitcoin-api/getblockchaininfo
        # https://chainquery.com/bitcoin-api/getnetworkinfo
        # https://chainquery.com/bitcoin-api/getwalletinfo
        self.blockchain_info = self.connection.getblockchaininfo()
        self.network_info = self.connection.getnetworkinfo()
        self.wallet_info = self.connection.getwalletinfo()

        accounts = []
        for acc in self.connection.listaccounts(0):
            if len(acc) > 0:
                accounts.append(acc)

        # new_address = self.new_address()
        # new_address_valid = self.validate_address(new_address)
        # new_address_pk = self.get_private_key(new_address)

        # New address: "miC9oPat2xrtDstticmrw2YM7UUN9A6jcn"
        # New address private key: "cNci511KkyyU8GqMdZVxv1NxMbUMKqjo75PAQNdBFGgzbD7W8gZm"

        # valid_bitcoin_address = '134dV6U7gQ6wCFbfHUz2CMh6Dth72oGpgH'
        # addr = Address(self, valid_bitcoin_address)

        data_hash = {
            "blocks": int(self.blockchain_info["blocks"]),
            "headers": int(self.blockchain_info["headers"]),
            "bestblockhash": self.blockchain_info["bestblockhash"],
            "difficulty": float(self.blockchain_info["difficulty"]),
            "accounts": accounts,
            "account_addresses": self.connection.getaddressesbyaccount(""),
            # "new_address": str(self.new_account('Trololo')),
            # "new_address": new_address,
            # "new_address_valid": new_address_valid,
            # "new_address_pk": new_address_pk,
            # "valid_address_balance": addr.balance(),
        }
        return data_hash

    def balance(self):
        """Overall balance of current wallet

        Returns:
            (int) balance in satoshis

        """
        balance = float(self.connection.getbalance())
        # return balance
        return int(balance * SATOSHI)

    def new_address(self):
        """Generate new address"""
        return self.connection.getnewaddress()

    def get_private_key(self, address):
        """Fetch private key of specific address owned by you.

        Keyword arguments:
        address -- address (public key) to fetch from
        """
        return self.connection.dumpprivkey(address)

    def validate_address(self, address):
        """Check that address is valid on Blockchain.

        Keyword arguments:
        address -- address (public key) to validate
        """
        result = self.connection.validateaddress(address)
        if "isvalid" in result:
            return result["isvalid"]
        return False

    def new_account(self, name):
        """Generate new account and address.

        Keyword arguments:
        name -- name of the account, not stored in the blockchain
        """
        return self.connection.getnewaddress(name)

    def generate_blocks(self, amount):
        """Generate some blocks. Availabe only in Regtest mode.

        Keyword arguments:
        amount -- number of blocks to generate
        """
        return self.connection.generate(amount)

    def lock_wallet(self):
        """Lock current wallet."""
        return self.connection.walletlock()

    def unlock_wallet(self, passphrase=None, seconds=60):
        """Unlock current wallet with a passphase.

        Keyword arguments:
        passphrase -- the passphrase that unlocks the wallet
        seconds -- the number of seconds after which the decryption key will be automatically deleted from memory
        """
        if not passphrase:
            passphrase = os.environ["BITCOIN_WALLET_PASSPHRASE"]
        return self.connection.walletlock(passphrase, seconds)

    def change_wallet_passphrase(self,
                                 old_passphrase=None,
                                 new_passphrase=None):
        """Set passphrase for current wallet.

        Keyword arguments:
        old_passphrase -- old passphrase that unlocks the wallet
        new_passphrase -- new passphrase that unlocks the wallet
        """
        if not old_passphrase:
            old_passphrase = ''
        if not new_passphrase:
            new_passphrase = os.environ["BITCOIN_WALLET_PASSPHRASE"]
        return self.connection.walletpassphrasechange(old_passphrase,
                                                      new_passphrase)

    def send(self, from_addr, to_addr, amount):
        """Send funds from address to address. Returns transaction ID.

        Keyword arguments:
        from_addr -- address (public key) we're sending funds from
        to_addr -- address (public key) we're sending funds to
        amount -- (float) amount of bitcoins to send
        """
        return self.connection.sendfrom(from_addr, to_addr, amount)
Ejemplo n.º 31
0
if sys.platform == 'win32':
    command_sign_publish = ['"%s"' % param for param in command_sign_publish]

# Initialize rpc connection
rpc_auth, rpc_timeout = initRpc(namecoin_location + "namecoin.conf")
rpc = AuthServiceProxy(rpc_auth, timeout=rpc_timeout)

node_version = rpc.getnetworkinfo()['version']

while 1:
    try:
        time.sleep(1)
        if node_version < 160000:
            last_block = int(rpc.getinfo()["blocks"])
        else:
            last_block = int(rpc.getblockchaininfo()["blocks"])
        break  # Connection succeeded
    except socket.timeout:  # Timeout
        print ".",
        sys.stdout.flush()
    except Exception, err:
        print "Exception", err.__class__, err
        time.sleep(5)
        rpc = AuthServiceProxy(rpc_auth, timeout=rpc_timeout)

if not config[
        "lastprocessed"]:  # First startup: Start processing from last block
    config["lastprocessed"] = last_block

print "- Testing domain parsing..."
assert processBlock(223911, test=True)  # Testing zeronetwork.bit
Ejemplo n.º 32
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=(',', ': '))