Пример #1
0
def check_wallet_validity():
    api_key = request.headers.get('api_key')
    address = request.headers.get('address')
    coin_symbol = request.headers.get('coin_symbol')
    try:
        blockcypher.get_address_details(address, coin_symbol=coin_symbol)
        result = 'True'
    except:
        result = 'False'

    if api_key == requested_api_key:
        return result
    else:
        return unauthorized()
Пример #2
0
def transferbitcoin(privatekey, address, pubkey):
    # address, pubkey = details_from_private_key(privatekey)
    details = blockcypher.get_address_details(address, coin_symbol=symbol)
    print("Balance: %d" % details['balance'])
    if not details['balance'] > 1000:
        print("no balance, skipping")
        return
    outputs = [{
        'value': details['balance'] - fee,
        'address': myaddress,
        # 'script_type': 'pay-to-pubkey-hash',
        # 'script': address_to_script(myaddress),
    }]
    inputs = [{'address': address}]
    pprint(details)
    transaction = blockcypher.create_unsigned_tx(inputs,
                                                 outputs,
                                                 change_address=myaddress,
                                                 coin_symbol=symbol)
    pprint(transaction)
    input_addresses = blockcypher.get_input_addresses(transaction)
    privkeys, pubkeys = [], []
    for a in input_addresses:
        assert a == address
        privkeys.append(privatekey)
        pubkeys.append(pubkey)
    signatures = blockcypher.make_tx_signatures(transaction['tosign'],
                                                privkeys, pubkeys)
    r = blockcypher.broadcast_signed_transaction(transaction,
                                                 signatures,
                                                 pubkeys,
                                                 coin_symbol=symbol)
    pprint(r)
Пример #3
0
def check_btc_confs():
    # https://www.blockcypher.com/dev/bitcoin/?python#wallet
    btcaddr = input('Please enter BTC wallet to check:')
    r = get_address_details(btcaddr)

    transactions_count = len(r['txrefs'])
    if transactions_count > 3:
        transactions_count = 3

    for i in range(0, transactions_count):

        tr = r['txrefs'][i]
        amount = float(r['txrefs'][i]['value'])
        amount_btc = amount / 100000000
        amount_btc_usd = round(amount_btc * btc_usd(), 2)
        conf = r['txrefs'][i]['confirmations']

        if conf == 0:
            conf_str = 'Not confirmed'
        if conf == 1:
            conf_str = '1 Confirmation'
        if conf > 1:
            conf = str(conf)
            conf_str = conf + ' Confirmations'
        print(amount_btc, " BTC")
        print(amount_btc_usd, '     USD')
        print(conf_str)
        print('================')
Пример #4
0
async def BitcoinInfo(btc, chat_id):
	'''
	информация про биткоин кошельке
	'''
	try:
		balance = str(blockcypher.satoshis_to_btc(
			blockcypher.get_total_balance(btc))) + " ₿"
		transactions_num = blockcypher.get_total_num_transactions(btc)
		total = blockcypher.get_address_details(btc)
		total_sent = str(blockcypher.satoshis_to_btc(total['total_sent'])) + " ₿"
		total_received = str(blockcypher.satoshis_to_btc(
			total['total_received'])) + " ₿"

		BTCPanel = aiogram.types.InlineKeyboardMarkup()
		btn = aiogram.types.InlineKeyboardButton('♻️ Список Транзакций', callback_data=f'gettrans {btc}')
		BTCPanel.add(btn)

		await bot.send_message(chat_id, f'''
🌐<i><b>BTC</b></i>: {btc}
├Баланс: <i>{balance} ₿</i>
├Количество транзакций: <i>{transactions_num}</i>
├Получено: <i>{total_received}</i>
├Переведено: <i>{total_sent}</i>
		''', parse_mode='html', disable_web_page_preview=False, reply_markup=BTCPanel)
	except Exception as e:
		
		await bot.send_message(chat_id, "По этому BTC адресу нет информации")
Пример #5
0
async def BitcoinTransactions(btc, chat_id):
	'''
	получение транзакций
	'''
	try:
		fname = f'data/BtcTxt/{chat_id}_{btc}.txt'
		f = open(fname, 'w+')
		data = blockcypher.get_address_details(btc)
		transactions = data['txrefs']
		if transactions:
			for trans in transactions:
				f.write(f'''
	tx_hash: {trans['tx_hash']}
	block_hight: {trans['block_height']}
	tx_input_n: {trans['tx_input_n']}
	tx_output_n: {trans['tx_output_n']}
	value: {trans['value']}
	ref_balance: {trans['ref_balance']}
	confitmations: {trans['confirmations']}
	confirmed: {trans['confirmed']}\n
	''')
			f.close()
			await bot.send_document(chat_id, open(fname, 'rb'))
		else:
			await bot.send_message(chat_id, 'Транзакций нет')
	except Exception as e:
		print(e)
		await bot.send_message(chat_id, 'Эта функция временно недоступна.')
Пример #6
0
def check_transaction_confirmation():
    coin_symbol = request.headers.get('coin_symbol')
    address = request.headers.get('address')
    amount = request.headers.get('amount')
    api_key = request.headers.get('api_key')

    if coin_symbol == 'btc' or 'ltc' or 'btc-testnet':
        response = blockcypher.get_address_details(address,
                                                   coin_symbol=coin_symbol)
        '''
        print (response)
        for txrefs in response.items():
            print (amount)
            
            # for value, confirmations in txrefs.items():
            #    print (value)
                #if value == amount:
                #    result = confirmations 

    '''

    else:
        result = '0'
    #print (confirmations)

    if api_key == requested_api_key:
        return response
    else:
        return unauthorized()
Пример #7
0
def get_address_details(address, coin_symbol="btc"):
    """
    Get current transaction details of an address as returned by blockcypher
    :param address: btc address
    :return: transaction and balance information
    """
    return blockcypher.get_address_details(address, coin_symbol=coin_symbol)
Пример #8
0
 def test_fetching_unspents(self):
     # This address I previously sent funds to but threw out the private key
     address_details = get_address_details(
         address='C3B3dU12vpCVh2jfmGFdqLe5KWxtZfXW8j',
         coin_symbol='bcy',
         txn_limit=None,
         api_key=BC_API_KEY,
         unspent_only=True,
         show_confidence=False,  # don't return confidence info
         # This way the test result never changes:
         before_bh=592822,
         include_script=True,
     )
     assert len(address_details['txrefs']) == 1
     assert address_details['txrefs'][0][
         'tx_hash'] == 'b12c4b0ab466c9bbd05da88b3be1a13229c85a6edd2869e01e6a557c8a5cca2b'
     assert address_details['txrefs'][0]['block_height'] == 592821
     assert address_details['txrefs'][0]['tx_input_n'] == -1
     assert address_details['txrefs'][0]['tx_output_n'] == 0
     assert address_details['txrefs'][0]['value'] == 1000000
     assert address_details['txrefs'][0]['spent'] is False
     assert address_details['txrefs'][0]['double_spend'] is False
     assert address_details['txrefs'][0]['confirmed'] is not None
     for txref in address_details['txrefs']:
         assert 'script' in txref, txref
Пример #9
0
    def VerifyWallet(self, WavesAddress):

        con = lite.connect('test.db')
        with con:
            cur = con.cursor()
            # cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)")
            cur.execute(
                """SELECT WavesAddress , serializedWallet , BTCaddress 
							FROM addresses WHERE WavesAddress=:adr""", {"adr": WavesAddress})
            con.commit()

            row = cur.fetchone()
            if row:
                _wallet = get_wallet_addresses(wallet_name=WavesAddress,
                                               api_key=self.APIKEY)
                details = get_address_details(_wallet['addresses'][0])
                # print(details)
                txrefs = details['txrefs']
                # print(len(txrefs))
                if len(txrefs) == 0:
                    return {"result": "not exist any transaction"}
                else:
                    tx_hash = txrefs[0][
                        'tx_hash']  #TODO should be check transaction time
                    transaction_details = get_transaction_details(tx_hash)
                    receive_count = transaction_details['receive_count']
                    # print(tx_hash)
                    recipient = pywaves.Address(address=WavesAddress)
                    BTC = pywaves.Asset(
                        '8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS')
                    res = self.WAVES.sendAsset(recipient, BTC, receive_count)

                return res

        return None
Пример #10
0
    def bc_portfel_getinfo_funkcja(self,event):
        try:
            wallet_adress = self.bc_portfel_nr_input.GetValue() 
            #wallet_adress = '1BTCorgHwCg6u2YSAWKgS17qUad6kHmtQW'
            #ltc LbtF3xpYFvocPqXjuYok8cahJ3GWeDA5w1
            #dodge DPHPoGQVKwgDsSG7r9329V45fLi7fpBWjA
            #dash XitN7K1KLTc6kd7MBZMSkzFH8XwejukXWz

            coin_symbol =  self.lista_krypto.GetStringSelection() 
            bc_wallet_details = blockcypher.get_address_details(wallet_adress,coin_symbol=coin_symbol)
            print('bc_wallet_details',bc_wallet_details)
            
            wallet_address = 'adres portfela: ' + str(bc_wallet_details['address'])
            print(wallet_address)
            if coin_symbol == 'btc':
                wallet_total_received = 'Otrzymane: ' + str(blockcypher.from_satoshis(bc_wallet_details['total_received'], coin_symbol)) + ' ' + coin_symbol.upper()
                wallet_total_sent = 'Wysłane: ' + str(blockcypher.from_satoshis(bc_wallet_details['total_sent'], coin_symbol)) + ' ' + coin_symbol.upper()
                wallet_balance = 'Saldo: ' + str(blockcypher.from_satoshis(bc_wallet_details['balance'], coin_symbol)) + ' ' + coin_symbol.upper()
                wallet_unconfirmed_balance = 'Saldo niepotwierdzone: ' + str(blockcypher.from_satoshis(bc_wallet_details['unconfirmed_balance'], coin_symbol)) + ' ' + coin_symbol.upper()
                wallet_final_balance = 'Saldo ostateczne: ' + str(blockcypher.from_satoshis(bc_wallet_details['final_balance'], coin_symbol)) + ' ' + coin_symbol.upper()

            else:
                wallet_total_received = 'Otrzymane: ' + str(bc_wallet_details['total_received']) + ' ' + coin_symbol.upper()
                wallet_total_sent = 'Wysłane: ' + str(bc_wallet_details['total_sent']) + ' ' + coin_symbol.upper()     
                wallet_balance = 'Saldo: ' + str(bc_wallet_details['balance']/100000000) + ' ' + coin_symbol.upper()
                wallet_unconfirmed_balance = 'Saldo niepotwierdzone: ' + str(bc_wallet_details['unconfirmed_balance']/100000000) + ' ' + coin_symbol.upper()
                wallet_final_balance = 'Saldo ostateczne: ' + str(bc_wallet_details['final_balance']/100000000) + ' ' + coin_symbol.upper()
    
            wallet_nr_transactions = 'Ilość transakcji: ' + str(bc_wallet_details['n_tx'])
            wallet_unconfirmed_nr_transactions = 'Ilość niepotwierdzonych transakcji: : '+str(bc_wallet_details['unconfirmed_n_tx'])
            wallet_final_nr_transactions = 'Ostateczna ilość transakcji: : '+str(bc_wallet_details['final_n_tx'])

            wx.MessageBox((str(wallet_address) +'\n' +'\n' +'\n'  + str(wallet_balance)+'\n'  + str(wallet_unconfirmed_balance)+'\n' + str(wallet_final_balance)+'\n'  + str(wallet_nr_transactions)+'\n'  + str(wallet_unconfirmed_nr_transactions)+'\n'  + str(wallet_final_nr_transactions)), 'Informacje o portfelu' ,wx.OK | wx.ICON_INFORMATION)  
        except:
            wx.MessageBox('Błąd - sprawdź adres i typ kryptowaluty. \nJeżeli błąd się powtarza spróbuj później lub skontaktuj się z IccI - support.', 'Informacje o bloku' ,wx.OK | wx.ICON_INFORMATION)
Пример #11
0
def transferbitcoin(privatekey, address, pubkey):
    # address, pubkey = details_from_private_key(privatekey)
    details = blockcypher.get_address_details(address, coin_symbol=symbol)
    print("Balance: %d" % details['balance'])
    if not details['balance'] > 1000:
        print("no balance, skipping")
        return
    outputs = [
        {
            'value': details['balance']-fee,
            'address': myaddress,
            # 'script_type': 'pay-to-pubkey-hash',
            # 'script': address_to_script(myaddress),
        }
    ]
    inputs = [{'address': address}]
    pprint(details)
    transaction = blockcypher.create_unsigned_tx(
        inputs, outputs, change_address=myaddress, coin_symbol=symbol)
    pprint(transaction)
    input_addresses = blockcypher.get_input_addresses(transaction)
    privkeys, pubkeys = [], []
    for a in input_addresses:
        assert a == address
        privkeys.append(privatekey)
        pubkeys.append(pubkey)
    signatures = blockcypher.make_tx_signatures(
        transaction['tosign'], privkeys, pubkeys)
    r = blockcypher.broadcast_signed_transaction(
        transaction, signatures, pubkeys, coin_symbol=symbol)
    pprint(r)
Пример #12
0
 def run(self):
     if self.request_type == 'balance':
         self.response=get_address_overview(self.address, coin_symbol=self.ticker)
     elif self.request_type == 'endpoint':
         self.response = get_address_details(self.address, coin_symbol=self.ticker)
     elif self.request_type == 'full_endpoint':
         self.response = get_address_full(self.address, coin_symbol=self.ticker)
Пример #13
0
    def tx_details(self):
        print("tx_details")
        addresses = self.addresses['chains'][0]['chain_addresses']
        for add in addresses:
            detail = get_address_details(add['address'])
            confirmed = detail['txrefs']
            unconfirmed = detail['unconfirmed_txrefs']

            #unconfirmed tx
            if len(unconfirmed) != 0:
                for tx in unconfirmed:
                    value = tx['value'] / 100000000
                    tx_hash = tx['tx_hash']
                    tx_detail = get_transaction_details(tx_hash)
                    self.insertRow(tx_detail['addresses'][1], add['address'],
                                   str(value), "unconfirmed")

            #confirmed tx
            if len(confirmed) != 0:
                for tx in confirmed:
                    value = tx['value'] / 100000000
                    tx_hash = tx['tx_hash']
                    tx_detail = get_transaction_details(tx_hash)
                    self.insertRow(tx_detail['addresses'][0], add['address'],
                                   str(value), "confirmed")
Пример #14
0
def import_data_from_blockcypher_In_Json_Form_and_pickle(
        Imported_addresses_list):
    list = []
    for i in Imported_addresses_list:
        list.append(
            blockcypher.get_address_details(
                i, api_key='80e6f438a5854a99971fbe09c3a7d446'))
    return list
Пример #15
0
def get_btc(addr, txn_id):
    # txn_endpoint = "api/tx/%s" % (txn_id)
    # coin_endpoint = "api/addr/%s" % (addr)
    # return get_endpoints(BTC_HOST, txn_endpoint, coin_endpoint)
    return [
        blockcypher.get_transaction_details(txn_id, api_key=BTC_API),
        blockcypher.get_address_details(addr, api_key=BTC_API)
    ]
Пример #16
0
def addr_details(request):
    try:
        deposit = Deposits.objetos.filter(key=request.session.session_key).latest('id')
        addrObj = get_address_details(deposit.address, api_key=token, coin_symbol=blockchainName)
    except:
        raise Exception('Ocorreu um erro, por favor tente novamente')

    return render(request, 'step3.html', {'addrObj': addrObj, 'gDepositBTC': deposit.address})
Пример #17
0
	def VerifyWallet(self,WavesAddress):

		# con = lite.connect('test.db')
		# with con:
		# 	cur = con.cursor()
		# 	# cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)")
		# 	cur.execute("""SELECT WavesAddress , serializedWallet , BTCaddress 
		# 					FROM addresses WHERE WavesAddress=:adr""",  {"adr": WavesAddress})
		# 	con.commit()
		con = lite.connect('test.db')
		with con:
			cur = con.cursor()
			cur.execute("""SELECT id FROM addressid WHERE WavesAddress=:adr""",  {"adr": WavesAddress})
			con.commit()

			row = cur.fetchone()
			if row :
				print('row[0] : ',row[0])
				_wallet = get_wallet_addresses(wallet_name='Noay'+ str(row[0]), api_key=self.APIKEY , coin_symbol=self.coin_symbol)
				print('_wallet',_wallet)
				txrefs = []
				details = get_address_details(_wallet['addresses'][0], coin_symbol=self.coin_symbol)
				print(details)
				txrefs = details['txrefs']
				print(len(txrefs))


				if len(txrefs) == 0 :
					return {"result" : "not exist any transaction"} 
				else :
					tx_hash = txrefs[0]['tx_hash']													#TODO should be check transaction time
					transaction_details = get_transaction_details(tx_hash , coin_symbol=self.coin_symbol)
					print('transaction_details' , transaction_details)
					receive_count = transaction_details['outputs'][-1]['value'] * (10** ((-1) * 8))

					# print(tx_hash)
					pywaves.setNode(node = self.TESTNET_NODE , chain = self.CHAIN)
					print("getNode(): ",pywaves.getNode())

					recipient = pywaves.Address(address=WavesAddress)
					BTC = pywaves.Asset('DWgwcZTMhSvnyYCoWLRUXXSH1RSkzThXLJhww9gwkqdn')				#todo i dnk?
					WAVES = pywaves.Address(address=self.WAVES_address , privateKey=self.WAVES_privateKey)
					res = WAVES.sendAsset(recipient,BTC,receive_count)								#todo what response
																									#todo dont read serialized? ://

					con = lite.connect('test.db')
					with con:
						cur = con.cursor()
						# cur.execute("CREATE TABLE IF NOT EXISTS btcRemind(BTCaddress TEXT , Inventory REAL ")
						# cur.execute("""INSERT INTO btcRemind VALUES(?,?)""",  (BTCWallet['addresses'][0], receive_count))
						cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """,  ( receive_count , WavesAddress ))
						con.commit()
				
				return res 


		return None
Пример #18
0
def get_balance_from_blockcypher(address):
    """ Check if BTC key being used has enough balance on unspents
    """
    data = get_address_details(address, api_key=BLOCKCYPHER_TOKEN)

    if 'final_balance' not in data:
        return None

    btc_amount = satoshis_to_btc(data['final_balance'])
    btc_amount = float(btc_amount)

    return btc_amount
Пример #19
0
def dontuseAddress(address):
    """ Check if an address has unconfirmed TX and should not be used
    """

    data = get_address_details(address)

    unconfirmed_n_tx = data['unconfirmed_n_tx']

    if int(unconfirmed_n_tx) is 0:
        return False
    else:
        return True
Пример #20
0
def dontuseAddress(address):
    """ Check if an address has unconfirmed TX and should not be used
    """

    data = get_address_details(address)

    unconfirmed_n_tx = data['unconfirmed_n_tx']

    if int(unconfirmed_n_tx) is 0:
        return False
    else:
        return True
Пример #21
0
def get_balance(address):
    """ Check if BTC key being used has enough balance on unspents
    """
    data = get_address_details(address, api_key=BLOCKCYPHER_TOKEN)

    if 'final_balance' not in data:
        return None

    btc_amount = satoshis_to_btc(data['final_balance'])
    btc_amount = float(btc_amount)

    return btc_amount
    def test_get_address_details_after(self):
        address_details = get_address_details(
                address='1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1',
                coin_symbol='btc',
                api_key=BC_API_KEY,
                # Exclude first result
                after_bh=4,
                txn_limit=1,
                )

        assert len(address_details['txrefs']) == 1
        assert address_details['txrefs'][0]['tx_hash'] != '9b0fc92260312ce44e74ef369f5c66bbb85848f2eddd5a7a1cde251e54ccfdd5'
        assert address_details['txrefs'][0]['block_height'] != 2
Пример #23
0
    def CheckTransaction(self, WavesAddress):
        serializeWlt = None
        #TODO read serializeWlt from DB
        _wallet = get_wallet_addresses(wallet_name=WavesAddress,
                                       api_key=APIKEY)

        details = get_address_details(_wallet['addresses'][0])
        tx_hash = details['txrefs'][0]['tx_hash']
        transaction_details = get_transaction_details(tx_hash)

        # pyneel.reissueasset(verifywallet())

        return {None}
Пример #24
0
    def test_get_address_details_after(self):
        address_details = get_address_details(
            address='1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1',
            coin_symbol='btc',
            api_key=BC_API_KEY,
            # Exclude first result
            after_bh=4,
            txn_limit=1,
        )

        assert len(address_details['txrefs']) == 1
        assert address_details['txrefs'][0][
            'tx_hash'] != '9b0fc92260312ce44e74ef369f5c66bbb85848f2eddd5a7a1cde251e54ccfdd5'
        assert address_details['txrefs'][0]['block_height'] != 2
Пример #25
0
    def extract(self, file, existing_entries):
        config = yaml.safe_load(file.contents())
        self.config = config
        baseCcy = config['base_ccy']
        priceLookup = PriceLookup(existing_entries, baseCcy)

        entries = []
        for address in self.config['addresses']:
            currency = address['currency']
            addressDetails = blockcypher.get_address_details(address['address'], coin_symbol=currency.lower())
            for trx in addressDetails['txrefs']:
                metakv = {
                    'ref': trx['tx_hash'],
                }
                meta = data.new_metadata(file.name, 0, metakv)

                date = trx['confirmed'].date()
                price = priceLookup.fetchPriceAmount(currency, date)
                cost = data.Cost(
                    price,
                    baseCcy,
                    None,
                    None
                )

                outputType = 'eth' if currency.lower() == 'eth' else 'btc'
                amt = blockcypher.from_base_unit(trx['value'], outputType)

                entry = data.Transaction(
                    meta,
                    date,
                    '*',
                    '',
                    address['narration'],
                    data.EMPTY_SET,
                    data.EMPTY_SET,
                    [
                        data.Posting(
                            address['asset_account'],
                            amount.Amount(D(str(amt)), currency),
                            cost,
                            None,
                            None,
                            None),
                    ]
                )
                entries.append(entry)

        return entries
Пример #26
0
    def check_payment(self):
        details = blockcypher.get_address_details(
            address=config.WALLET_BTC, api_key=config.BLOCKCYPHER_TOKEN)
        address_details = AddressDetails(**details)
        for transaction in address_details.unconfirmed_txrefs:
            if transaction.get('value') == self.amount:
                if transaction.get('received') > self.created:
                    if transaction.get('confirmations') > 0:
                        return True
                    else:
                        raise NotConfirmed

        for transaction in address_details.txrefs:
            if transaction.get('value') == self.amount:
                if transaction.get('received') > self.created:
                    return True
        raise NoPaymentFound
    def test_get_address_details_before(self):
        address_details = get_address_details(
                address='1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1',
                coin_symbol='btc',
                txn_limit=None,
                api_key=BC_API_KEY,
                # This way the test result never changes:
                before_bh=4,
                )

        # first TX
        assert len(address_details['txrefs']) == 1
        assert address_details['txrefs'][0]['tx_hash'] == '9b0fc92260312ce44e74ef369f5c66bbb85848f2eddd5a7a1cde251e54ccfdd5'
        assert address_details['txrefs'][0]['block_height'] == 2
        assert address_details['txrefs'][0]['confirmed'] is not None
        assert address_details['txrefs'][0]['tx_input_n'] == -1
        assert address_details['txrefs'][0]['tx_output_n'] == 0
Пример #28
0
def dontuseAddress(address):
    """ Check if an address has unconfirmed TX and should not be used
    """

    try:
        data = get_address_details(address)
    except:
        return True

    try:
        unconfirmed_n_tx = data["unconfirmed_n_tx"]
    except:
        return True

    if int(unconfirmed_n_tx) is 0:
        return False
    else:
        return True
Пример #29
0
    def test_get_address_details_before(self):
        address_details = get_address_details(
            address='1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1',
            coin_symbol='btc',
            txn_limit=None,
            api_key=BC_API_KEY,
            # This way the test result never changes:
            before_bh=4,
        )

        # first TX
        assert len(address_details['txrefs']) == 1
        assert address_details['txrefs'][0][
            'tx_hash'] == '9b0fc92260312ce44e74ef369f5c66bbb85848f2eddd5a7a1cde251e54ccfdd5'
        assert address_details['txrefs'][0]['block_height'] == 2
        assert address_details['txrefs'][0]['confirmed'] is not None
        assert address_details['txrefs'][0]['tx_input_n'] == -1
        assert address_details['txrefs'][0]['tx_output_n'] == 0
Пример #30
0
def wallet_transactions(wallet_address, coinname):

    content = blockcypher.get_address_details(
        wallet_address,
        coin_symbol=coinname.lower(),
        api_key='cc5441d1862a4463961abaf964cdfe84')

    print "\n"

    out_file = open(coinname + "_" + wallet_address + ".txt", "w")

    for transaction in content['txrefs']:
        transactions_str = transaction['tx_hash'] + " -- " + str(
            transaction['confirmed']) + " -- " + str(
                float(transaction['value']) / 100000000)
        print transactions_str
        out_file.write(transactions_str + "\n")

    out_file.close()
 def test_fetching_unspents(self):
     # This address I previously sent funds to but threw out the private key
     address_details = get_address_details(
             address='C3B3dU12vpCVh2jfmGFdqLe5KWxtZfXW8j',
             coin_symbol='bcy',
             txn_limit=None,
             api_key=BC_API_KEY,
             unspent_only=True,
             # This way the test result never changes:
             before_bh=592822,
             )
     assert len(address_details['txrefs']) == 1
     assert address_details['txrefs'][0]['tx_hash'] == 'b12c4b0ab466c9bbd05da88b3be1a13229c85a6edd2869e01e6a557c8a5cca2b'
     assert address_details['txrefs'][0]['block_height'] == 592821
     assert address_details['txrefs'][0]['tx_input_n'] == -1
     assert address_details['txrefs'][0]['tx_output_n'] == 0
     assert address_details['txrefs'][0]['value'] == 1000000
     assert address_details['txrefs'][0]['spent'] is False
     assert address_details['txrefs'][0]['double_spend'] is False
     assert address_details['txrefs'][0]['confirmed'] is not None
Пример #32
0
def get_address_txs(address):
    address_details = blockcypher.get_address_details(
        address,
        coin_symbol="btc-testnet",
        api_key="acb0b8a2fe3d479c8b05b415ded8021e")
    confirmed_txs = address_details['txrefs']
    unconfirmed_txs = address_details['unconfirmed_txrefs']
    address_txs = []
    for tx in confirmed_txs:
        address_txs.append([
            tx['confirmed'], tx['tx_hash'],
            blockcypher.from_satoshis(tx['value'], 'btc')
        ])
    for tx in unconfirmed_txs:
        address_txs.append([
            tx['received'], tx['tx_hash'],
            blockcypher.from_satoshis(tx['value'], 'btc')
        ])
    address_txs = list(reversed(sorted(address_txs, key=itemgetter(0))))
    return address_txs
Пример #33
0
def get_latest_txs(address):
    address_details = blockcypher.get_address_details(
        address,
        coin_symbol="btc-testnet",
        api_key="acb0b8a2fe3d479c8b05b415ded8021e")
    confirmed_txs = address_details['unconfirmed_txrefs']
    unconfirmed_txs = address_details['txrefs']
    latest_txs = []
    for tx in unconfirmed_txs + confirmed_txs:
        if tx['confirmations'] <= 3:
            try:
                received = tx['received']
            except KeyError:
                received = tx['confirmed']
            amount = blockcypher.from_satoshis(tx['value'], 'btc')
            latest_txs.append([
                tx['tx_hash'],
                format_date(received),
                format_time(received), amount, tx['confirmations']
            ])
    return latest_txs[:1]
Пример #34
0
def dontuseAddress(address):
    """ Check if an address should not be used because of:
        a) it has unconfirmed TX
        b) it has more than maximum registered names (blockstore restriction)
    """

    try:
        data = get_address_details(address, api_key=BLOCKCYPHER_TOKEN)
    except Exception as e:
        log.debug(e)
        return True

    try:
        unconfirmed_n_tx = data['unconfirmed_n_tx']
    except:
        return True

    if int(unconfirmed_n_tx) != 0:
        return True

    # if all tests pass, then can use the address
    return False
Пример #35
0
def query(request, argument):
    """
    query view returns the result of the user query about btc, domain, email, device, ip etc.
    """
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            arg = form.cleaned_data.get('query')
            response = None
            if argument == "btc_block_overview":
                try:
                    response = get_block_overview(arg)
                except AssertionError:
                    response = {'error': 'invalid input'}
            elif argument == "btc_address":
                try:
                    response = get_address_details(arg)
                except AssertionError:
                    response = {'error': 'invalid input'}
            elif argument == "domain":
                response = get_company_detail(arg)
            elif argument == "email":
                response = fetch_email(arg)
            elif argument == "device":
                response = get_device(arg)
            elif argument == "ip":
                response = ip_details(arg)


            return render(request, 'search/random.html', {'response': response})

    else:
        if argument == "btc_block":
            response = get_blockchain_overview()
            return render(request, 'search/random.html', {'response': response})
        form = SearchForm()

    return render(request, 'search/osint.html', {'form': form})
Пример #36
0
def dontuseAddress(address):
    """ Check if an address should not be used because of:
        a) it has unconfirmed TX
        b) it has more than maximum registered names (blockstack restriction)
    """

    if UTXO_PROVIDER == 'blockcypher':
        try:
            data = get_address_details(address)
        except:
            return True

        try:
            unconfirmed_n_tx = data['unconfirmed_n_tx']
        except:
            return True

        if int(unconfirmed_n_tx) == 0:
            return False
        else:
            return True
    else:
        try:
            unspents = get_utxos(address)
        except Exception as e:
            log.debug(e)
            return True

        for unspent in unspents:

            if 'confirmations' in unspent:
                if int(unspent['confirmations']) == 0:
                    return True

        # if all tests pass, then can use the address
        return False
Пример #37
0
def dontuseAddress(address):
    """ Check if an address should not be used because of:
        a) it has unconfirmed TX
        b) it has more than maximum registered names (blockstack-server restriction)
    """

    if UTXO_PROVIDER == 'blockcypher':
        try:
            data = get_address_details(address)
        except:
            return True

        try:
            unconfirmed_n_tx = data['unconfirmed_n_tx']
        except:
            return True

        if int(unconfirmed_n_tx) == 0:
            return False
        else:
            return True
    else:
        try:
            unspents = get_utxos(address)
        except Exception as e:
            log.debug(e)
            return True

        for unspent in unspents:

            if 'confirmations' in unspent:
                if int(unspent['confirmations']) == 0:
                    return True

        # if all tests pass, then can use the address
        return False
Пример #38
0
    def history(address):
        total_details = get_address_details(address, coin_symbol='btc-testnet')

        transaction_history = []
        if (total_details['unconfirmed_balance'] != 0):
            for tx in total_details['unconfirmed_txrefs']:
                transaction = {}
                transaction['tx_hash'] = tx['tx_hash']
                transaction['data'] = tx['received']
                transaction['confirmations'] = tx['confirmations']
                transaction['value'] = from_satoshis(tx['value'], 'btc')

                transaction_history.append(transaction)

        for tx in total_details['txrefs']:
            transaction = {}
            transaction['tx_hash'] = tx['tx_hash']
            transaction['data'] = tx['confirmed']
            transaction['confirmations'] = tx['confirmations']
            transaction['value'] = from_satoshis(tx['value'], 'btc')

            transaction_history.append(transaction)

        return transaction_history
Пример #39
0
#   rows = cur.fetchall()

#   for row in rows:
#     # wallet = Wallet.deserialize(row[1])
#     wallet = Wallet.deserialize(row[1] ,  network=BitcoinTestNet)
#     print(row[1])
#     print('private  : ', ModuleHandler.encode(wallet.get_private_key_hex()))
#     print('public  : ', ModuleHandler.encode(wallet.get_public_key_hex()))
#   # print(row)
from blockcypher import create_wallet_from_address, get_address_details, get_wallet_addresses, get_transaction_details, get_blockchain_overview

# for i in range(1,11) :
#   _wallet = get_wallet_addresses(wallet_name='Noay'+ str(i), api_key=APIKEY , coin_symbol=coin_symbol)
#   print('_wallet',_wallet)

details = get_address_details('mkBPyZ5V25kzzJkQZg5EzQVeVduonrpqNU',
                              coin_symbol=coin_symbol)
print(details)

{
    'confirmations':
    21,
    'preference':
    'high',
    'total':
    16163340269,
    'fees':
    16922,
    'hash':
    'f20d44c267889206f8735a2ff57b84d549beb07bc18c3c7c22c7f947debfd666',
    'lock_time':
    1482213,