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")
def btc_process_trans_id(tx_id, cur, con, coin_tx_list, coin_from_exchange, coin_to_exchange, wallet_id_number): wallet_id_number = wallet_id_number + 1 getcontext().prec = 10 transaction = get_transaction_details(tx_id) #print (transaction) for address in transaction["outputs"]: #print (int(transaction["fees"])) #print (address["value"]) #print (Decimal(coinQty[tx_id]) * -1 - int(transaction["fees"])) if ((address["value"]) >= (Decimal(coin_tx_list[tx_id].qty) * -1 - int(transaction["fees"]))) and \ ((address["value"]) <= (Decimal(coin_tx_list[tx_id].qty) * -1)): date_time = str(transaction['received']).split('.')[0] #date_time = str(datetime(transaction['received'])).split('.')[0] if "spent_by" in address.keys(): child = address["spent_by"] else: child = "wallet" cur.execute("INSERT INTO wallets ( id, disposition, filename, coin, datetime, tx_id, tx_value, wallet, " + "wallet_value, child, fees) VALUES (?,?,?,?,?,?,?,?,?,?,?);", (str(wallet_id_number), str(coin_tx_list[tx_id].type), str(coin_tx_list[tx_id].fn), 'BTC', str(date_time), tx_id, str(Decimal(address["value"])/SATOSHI), str(address['addresses'][0]), str(Decimal(get_address_overview(address["addresses"][0])["final_balance"])/SATOSHI), str(child), str(Decimal(transaction["fees"])/SATOSHI))) con.commit() # date = datetime.date(time_trans) # print datetime.time(time_trans) #print ("date of transaction:", str(date_time)) #print ("found it at address:", str(address['addresses'][0])) #print ("Inital Value of address:", str(address["value"])) #print ("output transaction:", str(child)) #print ("address final Balance:", str(get_address_overview(address["addresses"][0]) # ["final_balance"])) # if tx_id == '8615b09eab97769d7e5da6aafac57655bcf1c868e5a75e09a91accabb38a6acd': btc_wallet_recurs(child, address['addresses'][0], address["value"], str(wallet_id_number) + '.1', cur, con, coin_tx_list, coin_from_exchange, coin_to_exchange)
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
def get_notarization_status(self, address, document_hash): notarization_data = self.get_notarization_by_document_hash(address, document_hash) status_data = get_transaction_details(notarization_data['transaction_hash'], config.get_coin_network()) if status_data is None: return None else: return status_data
def check_transaction_confirmations(): if settings.CHECK_TRANSACTION_CONFIRMATIONS: invoices = Invoice.objects.filter(is_paid=False, tx_ref__isnull=False) for invoice in invoices: if invoice.tx_ref and not invoice.is_expired: try: details = blockcypher.get_transaction_details( invoice.tx_ref, invoice.wallet.coin_symbol ) logger.info('Confirmatinos of transaction {} ({}): {}'.format( invoice.tx_ref, invoice.wallet.coin_symbol, details['confirmations'] ) ) if details['confirmations'] >= settings.DEFAULT_CONFIRMATIONS: invoice.is_paid = True invoice.save() invoice_is_paid.send( sender=Invoice, invoice_id=invoice.id ) logger.info('Invoice #{} successfully confirmed'.format( invoice.id ) ) except Exception as e: logger.exception('{}'.format(e))
def test_simple_spend_wif(self): tx_hash = simple_spend( from_privkey=self.bcy_privkey_wif, to_address=self.bcy_faucet_addr, to_satoshis=self.to_send_satoshis, privkey_is_compressed=False, api_key=BC_API_KEY, coin_symbol='bcy', ) # confirm details (esp that change sent back to sender address) tx_details = get_transaction_details( tx_hash=tx_hash, coin_symbol='bcy', api_key=BC_API_KEY, ) for input_obj in tx_details['inputs']: assert len(input_obj['addresses']) == 1, input_obj['addresses'] assert input_obj['addresses'][0] == self.bcy_pub_addr assert input_obj['script_type'] == 'pay-to-pubkey-hash' for output_obj in tx_details['outputs']: assert len(output_obj['addresses']) == 1, input_obj['addresses'] assert output_obj['script_type'] == 'pay-to-pubkey-hash' if output_obj['addresses'][0] == self.bcy_pub_addr: # this is change output_obj['value'] > 0 elif output_obj['addresses'][0] == self.bcy_faucet_addr: # this is the tx output_obj['value'] == self.to_send_satoshis else: raise Exception('Invalid Output Address: %s' % output_obj['addresses'][0])
def attest(self, txid): try: return get_transaction_details(txid, coin_symbol=settings.CHAIN) except Exception as e: self.logger.error( "[PoE ERROR] Error returning transantion details :{}, type({})" .format(e, type(e))) raise e
def attest(self, txid): try: return get_transaction_details(txid, coin_symbol=settings.CHAIN) except Exception as e: print( "[PoE ERROR] Error returning transantion details :%s, type(%s)" % (e, type(e))) raise e
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) ]
def get_raw_tx(tx_hash, coin_symbol): """ Takes the tx_hash, and return : 1) raw transaction of this tx in hex """ tx = get_transaction_details(tx_hash, coin_symbol, include_hex=True) return tx['hex']
def get_transaction_details(transaction_hash, coin_symbol="btc"): """ Get current transaction details of an hash as returned by blockcypher :param transaction_hash: btc address :return: transaction and balance information """ return blockcypher.get_transaction_details(transaction_hash, coin_symbol=coin_symbol)
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
async def on_message(self, message): if "!txid" in message.content: message_tx = re.search("(?<=!txid)(.*)", message.content) tx_id = message_tx[0].replace(" ", "") btc_info = get_transaction_details(tx_id) tx_amount = btc_info['total'] price = requests.get("https://blockchain.info/q/24hrprice") await message.channel.send( f"TXID: {tx_id} | Confirmations: {btc_info['confirmations']} | Date: {btc_info['received']} | Bitcoin Price (USD): {price.text}" )
def get_tx_confirmations(tx_hash): """ Return block height (currently uses BlockCypher API) """ resp = None try: data = get_transaction_details(tx_hash) # hack around bug where chain_com keeps broadcasting double spends if 'double_spend_tx' in data: data = get_transaction_details(data['double_spend_tx']) if 'confirmations' in data: resp = data['confirmations'] except Exception as e: log.debug("ERROR: tx details: %s" % tx_hash) log.debug(e) return resp
def check(txhash, hash): txdetails = get_transaction_details(txhash, coin_symbol='btc-testnet') outputs = txdetails['outputs'] for output in outputs: try: if output['data_hex'] == hash: return True except KeyError: pass return False
def get_tx_confirmations(tx_hash): """ Return block height (currently uses BlockCypher API) """ resp = None try: data = get_transaction_details(tx_hash) # hack around bug where chain_com keeps broadcasting double spends if "double_spend_tx" in data: data = get_transaction_details(data["double_spend_tx"]) if "confirmations" in data: resp = data["confirmations"] except Exception as e: log.debug("ERROR: tx details: %s" % tx_hash) log.debug(e) return resp
def initiate_transaction(): to_address = request.headers.get('to_address') to_satoshis = request.headers.get('to_satoshis') coin_symbol = request.headers.get('coin_symbol') api_key = request.headers.get('api_key') order_id = request.headers.get('order_id') if coin_symbol == 'btc': with open('./deposit_wallet/btc/wallet.json') as json_file: data = json.load(json_file) from_privkey = data['private'] if coin_symbol == 'btc-testnet': with open('./deposit_wallet/btc_testnet/wallet.json') as json_file: data = json.load(json_file) from_privkey = data['private'] if coin_symbol == 'ltc': with open('./deposit_wallet/ltc/wallet.json') as json_file: data = json.load(json_file) from_privkey = data['private'] #if coin_symbol == 'btc' or 'ltc' or 'btc-testnet': try: transaction_id = blockcypher.simple_spend(from_privkey=from_privkey, to_address=to_address, to_satoshis=int(to_satoshis), coin_symbol=coin_symbol, api_key=blockcypher_api_key, privkey_is_compressed=True) status = 'Success' except: status = 'Failure' #get current date and time current_date = datetime.datetime.now() #get transaction fee from tx id transaction_output = blockcypher.get_transaction_details( transaction_id, coin_symbol='btc-testnet') transaction_fee = float( transaction_output['fees']) / 100000000 #convert satoshi to bitcoin if api_key == requested_api_key: return { "transaction_id": transaction_id, "status": status, "timestamp": current_date.isoformat(), "order_id": order_id, "costomers_wallet": to_address, "transaction_amount": to_satoshis, "transaction_fee": transaction_fee } else: return unauthorized()
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}
def test_simple_spend_p2sh(self): from_addr = 'Dpuo6iMtoZW3oNsNuALHTEyyw55fBMxiqE' # keys that went into building from_addr all_from_pubkeys = [ '022d1d33c917e0c1ca677b8c6d47ee55b59880630afe8290517fc7de640ce257f5', '038a5f1bd7eeb34f53a014f81bfd50869cf6d972ee2bef078f6b67d4c8dd9432b2', '033796355300f6a50602f701fcf06baebf8b160553e100852703a9363522227a53', ] # 2 of 3 of the corresponding keys above from_privkeys_to_use = [ '57067d2852b5f92d18d82a09c2b658184eb85a38fe47adb8db85203a42f91e8f', 'c4bbc144bc5351288aa46c694a32eceaff739945510cca8bdd924d1c660ff1f4' ] tx_hash = simple_spend_p2sh( all_from_pubkeys=all_from_pubkeys, from_privkeys_to_use=from_privkeys_to_use, to_address=self.bcy_faucet_addr, to_satoshis=1, # change addr must be explicit: change_address=from_addr, coin_symbol='bcy', api_key=BC_API_KEY, ) # confirm details (esp that change sent back to sender address) tx_details = get_transaction_details( tx_hash=tx_hash, coin_symbol='bcy', api_key=BC_API_KEY, ) for input_obj in tx_details['inputs']: assert len(input_obj['addresses']) == 1, input_obj['addresses'] assert input_obj['addresses'][0] == from_addr assert input_obj['script_type'] == 'pay-to-script-hash' for output_obj in tx_details['outputs']: assert len(output_obj['addresses']) == 1, input_obj['addresses'] if output_obj['addresses'][0] == from_addr: # this is change assert output_obj['script_type'] == 'pay-to-script-hash' output_obj['value'] > 0 elif output_obj['addresses'][0] == self.bcy_faucet_addr: # this is the tx assert output_obj['script_type'] == 'pay-to-pubkey-hash' output_obj['value'] == 1 else: raise Exception('Invalid Output Address: %s' % output_obj['addresses'][0])
def value(self, testnet=False): '''Get the outpoint value by looking up the tx hash Returns the amount in satoshi ''' # use self.fetch_tx to get the transaction #tx = self.fetch_tx(testnet=testnet)#ORIGINAL # get the output at self.prev_index # return the amount property #return tx.tx_outs[self.prev_index].amount if testnet: coin_sym = "btc-testnet" else: coin_sym = "btc" pretx = get_transaction_details(self.prev_tx.hex(),coin_symbol=coin_sym) amount = pretx["outputs"][self.prev_index]["value"] return amount
def script_pubkey(self, testnet=False): '''Get the ScriptPubKey by looking up the tx hash Returns a Script object ''' # use self.fetch_tx to get the transaction #tx = self.fetch_tx(testnet=testnet)#ORIGINAL # get the output at self.prev_index # return the script_pubkey property #return tx.tx_outs[self.prev_index].script_pubkey if testnet: coin_sym = "btc-testnet" else: coin_sym = "btc" pretx = get_transaction_details(self.prev_tx.hex(),coin_symbol=coin_sym) ser_script = pretx["outputs"][self.prev_index]["script"] length = hex(int.from_bytes(encode_varint(len(ser_script)//2),"big"))[2:] script_pubkey = Script.parse(BytesIO(bytes.fromhex(length+ser_script))) return script_pubkey
def __Fetch_Merkle_root(self): if not self.zonefile: print 'No transaction found!' return False Tx_hash = self.zonefile['Tx_hash'] Tx = get_transaction_details(Tx_hash, coin_symbol='btc-testnet') for item in Tx['outputs']: for key in item: if (key == 'data_string'): #bisect.insort_left(self.Tx_list, (Tx['block_height'], item[key])); self.root = item[key] print self.root return True return False
def address_balance(self, address_id, confirmations=1): balance = 0 data = self.client.get_address_transactions(self.__account_id, address_id) transactions = data["data"] if 0 < len(transactions): for transaction in transactions: hash = transaction["network"]["hash"] # Txid transaction_sum = float( transaction["amount"] ["amount"]) # Сумма транзакции в виде 0.001 btc if 3 <= confirmations: """ Если нужно 3 или больше подтверждений сети, то проверяется транзакция на coinbase """ if self.__check_confirmation_from_coinbase(transaction): balance += transaction_sum elif confirmations in [1, 2]: """ Если нужно 2 или 3 конфирма """ transaction_info = blockcypher.get_transaction_details( hash) if "confirmations" in transaction_info: transaction_confirmations = transaction_info[ "confirmations"] elif self.__check_confirmation_from_coinbase(transaction): transaction_confirmations = 3 else: transaction_confirmations = 0 if confirmations <= transaction_confirmations: balance += transaction_sum elif 0 == confirmations: balance += transaction_sum return balance
def sweep_fund(privkey, address, coin_symbol, api_key): """ Takes private key and wallet address, sweep all the fund of this address, and return : 1) the tx_hash of sweeping transaction 2) remaining balance of the address """ tx_hash = simple_spend(from_privkey=privkey, to_address=address, to_satoshis=-1, coin_symbol=coin_symbol, api_key=api_key) tx = get_transaction_details(tx_hash, coin_symbol=coin_symbol) balance = tx['total'] print('balance:', balance) return tx_hash, balance
def convert_blockhash(cur, block_hash): cur.execute("select b.block_hash from block b where b.block_id in (select max(b2.block_id) from block b2)") res=cur.fetchone() if block_hash == res[0]: cur.execute("select tx_hash from block join block_tx bt on block.block_id=bt.block_id join tx on bt.tx_id=tx.tx_id where block_hash like %s", (block_hash,)) res=cur.fetchone() bid=res[0] dic=blockcypher.get_transaction_details(bid, 'ltc') bh=dic['block_hash'] return bh cur.execute("select block_id from block where block_hash like %s",(block_hash,)) res=cur.fetchone() if res is None: return bid=res[0] fid=find_follblock(cur, bid) cur.execute("select block_hashprev from orphan_block where block_id= %s",(fid,)) res=cur.fetchone() return res[0]
def test_unconfirmed_tx_confidence(self): # fetch a recent tx hash (assume BTC will always have an unconfirmed TX): recent_tx_hash = get_broadcast_transactions( coin_symbol='btc', api_key=BC_API_KEY, limit=1, )[0]['hash'] # get confidence info for it tx_details = get_transaction_details( tx_hash=recent_tx_hash, coin_symbol='btc', limit=1, tx_input_offset=None, tx_output_offset=None, include_hex=False, confidence_only=True, api_key=BC_API_KEY, ) assert 'receive_count' in tx_details, tx_details assert 'preference' in tx_details, tx_details assert 'age_millis' in tx_details, tx_details assert 'confidence' in tx_details, tx_details assert 0 <= tx_details['confidence'] <= 1, tx_details
def testnet_receive_coin(self): """" Metodo para recebimento de coins na rede testnet :return: Hash da transacao realizada :rtype: str """ try: datas = get_transaction_details(tx_hash=self.tx_hash, coin_symbol='bcy') except: raise ValidationError('Hash da transacao invalido ou nao ' 'identificado.') if datas.get('error'): raise ValidationError('Transacao nao encontrada.') vals = {'name': datas.get('hash')} if datas.get('confirmations') >= 2: vals.update({ 'confirmation': datas.get('confirmations'), 'date_time': str(datas.get('confirmed')), 'state': 'D', 'satoshi': datas.get('outputs')[0].get('value') }) self.write(vals) return datas.get('hash')
def get_data_from_tx(txs): transaction = get_transaction_details(txs) for x in transaction['outputs']: if x['script_type'] == 'null-data': print(x) return x['data_string'], transaction['received']
def bc_transakcja_getinfo_funkcja(self,event): try: transakcja_hash = self.bc_transakcja_nr_input.GetValue() #transakcja_hashbtc = '400f3daead6ce20f3b6e1639e041dff9f563ec8b87cfb33a95efd37b8883c6e4' #ltc 03ae8088de52d8073be112629dce77c588e34320ccc923630d60fc453b87b091 coin_symbol = self.lista_krypto.GetStringSelection() #transakcja bc_transaction_details = blockcypher.get_transaction_details(transakcja_hash,coin_symbol=coin_symbol) # BTC unless specified print('bc_transaction_details',bc_transaction_details) bc_trans_confirmed = 'Potwierdzone: ' + str(bc_transaction_details['confirmed']) bc_trans_received = 'Złożone: ' + str(bc_transaction_details['received']) #transakcja bc_number_of_confirmations = 'Ilość potwierdzeń: ' + str(blockcypher.get_num_confirmations(transakcja_hash,coin_symbol=coin_symbol)) #print('\n\nbc_number_of_confirmations',bc_number_of_confirmations) if coin_symbol == 'btc': #transakcja bc_satoshis_transacted = blockcypher.get_satoshis_transacted(transakcja_hash,coin_symbol=coin_symbol) #print('\n\nbc_satoshis_transacted',bc_satoshis_transacted) transaction_from_satoshi = 'Kwota: ' + str(blockcypher.from_satoshis(bc_satoshis_transacted,coin_symbol)) + ' ' +coin_symbol.upper() #print('transaction_from_satoshi',transaction_from_satoshi) else: #transakcja transaction_from_satoshi = 'Kwota: ' + str(bc_transaction_details['total']/100000000) + ' ' +coin_symbol.upper() #print('transaction_from_satoshi',transaction_from_satoshi) hash_transakcji = ('Hash_transakcji: '+str(transakcja_hash)) if coin_symbol == 'btc-testnet': block_hash = '' block_height = '' block_index = '' else: block_hash = 'Hash bloku: ' + str(bc_transaction_details['block_hash']) block_height = 'Wysokość: ' + str(bc_transaction_details['block_height']) block_index = 'Indeks bloku: ' + str(bc_transaction_details['block_index']) adresy = bc_transaction_details['addresses'] try: adres_zleceniodawcy = str(adresy[0]) adres_odbiorcy = str(adresy[1]) except: adres_zleceniodawcy = '' adres_odbiorcy = '' if coin_symbol == 'btc': transaction_fees = 'Opłaty: ' + str(blockcypher.from_satoshis(bc_transaction_details['fees'],coin_symbol)) + ' ' + coin_symbol.upper() else: transaction_fees = 'Opłaty: ' + str(bc_transaction_details['fees']/100000000) + ' ' + coin_symbol.upper() wx.MessageBox((str(hash_transakcji) +'\n\n'+ str(bc_number_of_confirmations) +'\n\n' + str(transaction_from_satoshi) + '\n' + transaction_fees +'\n\n' + bc_trans_confirmed+ '\n' + bc_trans_received +'\n\n'+ str(block_hash) +'\n\n' + str(block_height)+'\n' + str(block_index) +'\n\n' + 'Adres zleceniodawcy:'+ '\n'+ adres_zleceniodawcy +'\n\n' +'Adres odbiorcy:' + (adres_odbiorcy)+ '\n\n' ), 'Informacje o transakcji' ,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)
def cb_coin_to_database(fn, cur, con): # Process coinbase Coin csv file coin_tx_list = {} coin_to_exchange = [] coin_from_exchange = [] with open(fn[2], 'r') as fin: # `with` statement available in 2.5+ reader = csv.reader(fin) for row in reader: if (len(row) > 2) and (row[0].find("-") != -1): # first columnn includes a date qty = row[2] dollars = 0 if (row[7] == "") else -1 * Decimal(row[7]) coin = row[3] tx_id = row[21] coin_addr = row[4].replace("0x", "") # print tx_id, dollars pac_date_time = row[0].split(" ") # adjust for UTC time date_time = datetime.strptime(pac_date_time[0]+pac_date_time[1], "%Y-%m-%d%H:%M:%S") + \ timedelta(hours=COINBASE_DELTA_TIME_HR) if dollars != 0: # print ("usd:", str(row)) add_column_if_not_in_table("USD_C", cur, con) name = coin + "_C" add_column_if_not_in_table(name, cur, con) cur.execute( "INSERT INTO crypto (filename, datetime, type, %s, USD_C) VALUES (?, ?, ?, ?, ?);" % name, (fn[1], date_time, 'trade', str(qty), str(dollars))) con.commit() elif (dollars == 0) and (tx_id != ""): #print ("transfer:", str(row)) # name =coin+"_"+tx_id name = coin.upper() + "_C" add_column_if_not_in_table(name, cur, con) if "BTC" in name: #coinQty[tx_id] = Decimal(qty) * SATOSHI coin_tx_list[tx_id] = coinObject( Decimal(qty) * SATOSHI, fn[1], name, coin_addr) else: #coinQty[tx_id] = qty coin_tx_list[tx_id] = coinObject( Decimal(qty), fn[1], name, coin_addr) if Decimal(qty) < 0: coin_from_exchange.append(tx_id) # add here need to query else: if "BTC" in name: print(tx_id) transaction = get_transaction_details(tx_id) if 'addresses' in transaction['inputs'][0].keys(): coin_addr = transaction['inputs'][0][ 'addresses'][0] else: coin_addr = 'unparsed' print(coin_addr) coin_to_exchange.append(tx_id) wallet = coin.upper() + '_' + coin_addr[0:5] add_column_if_not_in_table(wallet, cur, con) #print (str(qty), ":", tx_id) cur.execute( "INSERT INTO crypto (filename, datetime, type, %s, %s, tx_id) VALUES (?, ?, ?, ?, ?,?);" % (name, wallet), (fn[1], date_time, 'xfer', qty, str(Decimal(qty) * -1), tx_id)) con.commit() #coinFn[tx_id] = fn[1] #coinType[tx_id] = name #coinAddr[tx_id] = coin_addr return [coin_tx_list, coin_from_exchange, coin_to_exchange]
def btc_wallet_recurs(tx_id, wallet, value, id_number, cur, con, coin_tx_list, coin_from_exchange, coin_to_exchange): child_tx_id = [] child_wallet = [] child_value = [] fees = "0" tx_id_total = value wallet_trans = wallet date_time = "" disposition = '' if tx_id != "wallet": #print ("tx_id:", str(tx_id)) #print ("wallet:", str(wallet)) #print ("value:", str(value)) transaction = get_transaction_details(tx_id) tx_id_total = value date_time = str(transaction['received']).split('.')[0] fees = transaction["fees"] wallet_trans = transaction['inputs'][0]["addresses"][0] #print (len(transaction['inputs'])) #print (transaction['inputs'][0]["addresses"][0]) #print (len(transaction['outputs'])) if len(transaction['inputs']) > 2: # note the tx_id as a possible exchange child_tx_id.append("exchange") elif len(transaction["outputs"]) > 2: # note the tx_id as a possible exchange child_tx_id.append("exchange") # elif tx_id in coinToExchange : # child_tx_id.append("exchange") else: # add tx_id to the wallet table for address in transaction["outputs"]: if "spent_by" in address.keys(): # Check to see if TXid and value Matches on in the Exchanges if (tx_id in coin_to_exchange) and (int(coin_tx_list[tx_id].qty) == address["value"]): #print (coinType[tx_id]) child_tx_id.append("exchange_"+ str(coin_tx_list[tx_id].type)) disposition = coin_tx_list[tx_id].type child_wallet.append("") child_value.append("") cur.execute("UPDATE crypto SET fee = '%s' WHERE tx_id = '%s' ;" % (str(-1*Decimal(fees)/SATOSHI), tx_id)) con.commit() cur.execute("UPDATE crypto SET %s = '%s' WHERE tx_id = '%s' ;" % ('BTC_'+transaction['inputs'][0]['addresses'][0][0:5],str(-1*(Decimal(fees) + Decimal(address['value']))/SATOSHI), tx_id)) con.commit() else: child_tx_id.append(address["spent_by"]) child_wallet.append(address['addresses'][0]) child_value.append(address["value"]) elif "value" in address.keys(): child_tx_id.append("wallet") child_wallet.append(address['addresses'][0]) child_value.append(value) if len(child_tx_id) == 1: child_tx_id_str = child_tx_id[0] else: child_tx_id_str = ",".join(child_tx_id) #print (tx_id) #print (Decimal(fees)) #print (Decimal(fees)) cur.execute("INSERT INTO wallets (id, disposition, coin, datetime, tx_id, tx_value, wallet, wallet_value, " + " child, fees) VALUES (?,?,?,?,?,?,?,?,?,?);", (str(id_number), str(disposition), 'BTC', str(date_time), tx_id, str(Decimal(tx_id_total)/SATOSHI), str(wallet_trans), str(get_address_overview(wallet_trans)["final_balance"]), str(child_tx_id_str), str(Decimal(fees)/SATOSHI))) con.commit() if len(child_tx_id) > 0: #print (len(child_tx_id)) for i in range(len(child_tx_id)): if "exchange" not in child_tx_id[i]: btc_wallet_recurs(child_tx_id[i], child_wallet[i], child_value[i], str(id_number)+'.'+str(i), cur, con)
def search_blockchain(search): try: # Try addresss category = 'address' search_id = search data = blockcypher.get_address_overview( search, coin_symbol="btc-testnet", api_key="acb0b8a2fe3d479c8b05b415ded8021e") except (AssertionError, TypeError): try: # Try block height category = 'block' block_height = blockcypher.get_block_height( search, coin_symbol='btc-testnet', api_key="acb0b8a2fe3d479c8b05b415ded8021e") search_id = block_height data = blockcypher.get_block_overview( block_height, coin_symbol="btc-testnet", api_key="acb0b8a2fe3d479c8b05b415ded8021e") except (AssertionError, TypeError): try: # Try block hash category = 'block' search_id = search data = blockcypher.get_block_overview( search, coin_symbol="btc-testnet", api_key="acb0b8a2fe3d479c8b05b415ded8021e") except (AssertionError, TypeError): try: # Try tx category = 'tx' search_id = search data = blockcypher.get_transaction_details( search, coin_symbol="btc-testnet", api_key="acb0b8a2fe3d479c8b05b415ded8021e") except (AssertionError, TypeError): category = None search_id = search data = None print(category) print(search_id) print(data) """ try: # address ??? data = get_from_bitcoind('getblock', [search]) data['message'] try: height_to_hash = get_from_bitcoind('getblockhash', [search]) data = get_from_bitcoind('getblock', [height_to_hash]) data['message'] try: data = get_from_bitcoind('getrawtransaction', [search, 1]) data['message'] category = None search_id = None except KeyError: category = 'tx' search_id = search except KeyError: category = 'block' search_id = search except KeyError: category = 'block' search_id = data['height'] # print('category: ', category) # print('search_id: ', search_id) # print('data: ', data) """ return category, search_id, data
import blockchain from blockcypher import get_transaction_details import requests requests.packages.urllib3.disable_warnings() #transcation_id=blockchain.embed("6cbe5d6c75bcabcd","e9eff5e2e97724ced567742d851b1053","btc-testnet") #transcation_id='02571d93e64340af193658b5b2b44cda7cc8660cac5dbb746d1d2765eca9f915' transcation_id='c640f0454cb1926ee82bf214ebe47f4bc12a197ed7104ef27c548aa7efb1224c' status_value=get_transaction_details(transcation_id,coin_symbol="btc-testnet") print status_value['confirmed']