Ejemplo n.º 1
0
def create_handler(request, order_total, btc_total):
    """
    Create a new bitcoin address if the latest created one has received funds.

    Otherwise use the latest address. The aim is to avoid 'address gap' issue.
    invoice_id should be something unique for the transaction.
    """
    invoice_id = str(request.cart.id)
    recv = BtcInvoice.objects.latest()
    address = recv.address
    received = get_address(address).total_received
    if received > 0:
        callback_url = _create_callback_url(
            request, invoice_id, settings.SECRET_KEY
        )
        recv = receive(settings.XPUB, callback_url, settings.API_KEY)
        address = recv.address
        invoice = BtcInvoice(
            invoice_id=invoice_id,
            price_in_usd=order_total,
            price_in_btc=btc_total,
            address=address
        )
        invoice.save()
    else:
        recv.price_in_usd = order_total
        recv.price_in_btc = btc_total
        recv.added_time = datetime.datetime.now(pytz.utc)
        recv.save()
        invoice_id = recv.invoice_id

    return (address, invoice_id)
Ejemplo n.º 2
0
class Lock(object):

    transaction = None
    public_address = None
    nonce = None
    nonce_flag = False

    def __init__(self):
        f = open('lock.txt', 'r')
        self.transaction = f.readline().rstrip()
        self.public_address = f.readline().rstrip()
        self.nonce = None
        self.nonce_flag = False
        if len(self.transaction) == 64:
            self.updateLock(1)

    def init_lock(self, address, trans):
        """ Initialize of global parameters storing lock address and transaction
            Can only be called once upon lock conception.

        :param: Public address associated with lock
        :param: Transaction associated with lock creation
        :return: String stating result of initalization call   
        """
        if len(self.transaction) == 64:
            return 'Propery has been Initialized previously'
        try:
            blockexplorer.get_tx(trans)
        except blockchain.exceptions.APIException, TypeError:
            return 'Invalid transaction'
        try:
            blockexplorer.get_address(address)
        except blockchain.exceptions.APIException, TypeError:
            return 'Invalid address'
Ejemplo n.º 3
0
def address():
    form = AddressSearchForm(request.form)

    if request.method == 'POST':
        addr = request.form['addr'].strip()
        try:
            clean_addr = str(addr)
            if len(clean_addr) == 34:
                try:
                    address = be.get_address(clean_addr, api_code=app.api_code)

                    return render_template(
                        '_address.html',
                        address=address,
                        search_value=addr,
                        current_time=datetime.now().strftime('LLL'))

                except APIException as e:
                    flash('API Error', 'warning')
                    return redirect(url_for('address'))
            else:
                message = 'The Bitcoin address is malformed.  Please check your data and try again.'
                flash(message, 'danger')
                redirect(url_for('address'))
        except (ValueError, TypeError) as err:
            message = 'An error has occurred: ' + str(err)
            flash(message, 'danger')
            return redirect(url_for('address'))
    else:
        return render_template('_address.html',
                               form=form,
                               current_time=datetime.now().strftime('LLL'))
Ejemplo n.º 4
0
def Main():

    print("***block data components***")
    hashValue = '000000000000000016f9a2c3e0f4c1245ff24856a79c34806969f5084f410680'
    blockDict = class_00.getBlockDict(hashValue)
    class_00.printDictvalue(blockDict)

    print("***transaction data components***")
    transactionDict = class_00.getTransactionDict(blockDict['transactions'])
    class_00.printDictvalue(transactionDict)

    print("***transaction output data***")
    outputDict = class_00.getOutputDict(transactionDict['outputs'])
    class_00.printDictvalue(outputDict)

    print("***address data components***")
    address = blockexplorer.get_address('1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd')
    addressDict = class_00.getAddressDict(address)
    class_00.printDictvalue(addressDict)

    print("***unspentoutputs data components***")
    outs = blockexplorer.get_unspent_outputs(
        '1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd')
    unspentoutputDict = class_00.getUnspentoutputsDict(outs[0])
    class_00.printDictvalue(unspentoutputDict)
Ejemplo n.º 5
0
def build(address, comment=""):
    # Builds the object with given attributes

    api_address = blockexplorer.get_address(address)
    api_transactions = api_address.transactions
    n_tx = api_address.n_tx
    total_received = api_address.total_received / 100000000
    total_sent = api_address.total_sent / 100000000
    balance = api_address.final_balance / 100000000
    if api_transactions:
        last_tx_date = api_transactions[0].time
    else:
        last_tx_date = 0
    #last_tx_date = datetime.utcfromtimestamp(api_transactions[-1].time).strftime('%Y-%m-%d %H:%M:%S')
    data_created_date = 0
    final_object = BitcoinAddress(address,
                                  n_tx,
                                  total_received,
                                  total_sent,
                                  balance,
                                  last_tx_date,
                                  data_created_date,
                                  comment,
                                  transactions=api_transactions)
    return final_object
Ejemplo n.º 6
0
def bitcoin_data(address):
    """
    Gather and format the Bitcoin data for a given address
    Output schema as Tuple:
        input address,
        output address,
        {
        input value
        output value
        transaction hash
        transaction time
        transaction relay
        }
    """
    transaction_pairs = []
    input_address = bce.get_address(address)
    transactions = input_address.transactions
    for event in transactions:
        for i in event.inputs:
            for o in event.outputs:
                transaction_pairs.append(tuple([i.address,
                                                o.address,
                                                {
                                                 'input_value': i.value,
                                                 'output_value': o.value,
                                                 'hash': event.hash,
                                                 'time': timestamp_conv(event.time),
                                                 'relay': event.relayed_by
                                                 }
                                                ]))
    return transaction_pairs
Ejemplo n.º 7
0
def extract_bitcoin_accounts(text):
    '''
    Extract posible bitcoin public keys
    :param text: Text to search the bitcoin public keys
    :return: List with bitcoin public keys, or None if there isn't
    '''
    # Regular expresion to detect bitcoin public keys. There aren't 0, I, O, and l
    regex = r"[1-3][123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{27,34}"
    bclist = re.findall(regex, text)

    bclist = list(set(bclist))  # Delete duplicates
    possible = len(bclist)
    ret = []

    # Look for the word bitcoin also
    if "BITCOIN" in text.upper() and len(bclist) > 0:
        for address in bclist:
            try:
                salida = blockexplorer.get_address(address,
                                                   limit=1,
                                                   api_code=apic)
                if len(salida.transactions) > 0:
                    ret.append(address)
            except Exception as e:
                logging.error(
                    "In function extract_bitcoins_accounts/blockexplorer API: {}"
                    .format(e))
                pass
        if len(ret) > 0:
            return ret, possible
        else:
            return None, possible
    else:
        return None, possible
Ejemplo n.º 8
0
def results(query):
    search_results = None
    type = None

    if len(query) > 63:
        try:
            search_results = be.get_block(query, api_code=app.api_code)
            type = 'Block Info'
        except APIException as e:
            print('An API error has occurred ' + str(e))
    elif len(query) > 33:
        try:
            search_results = be.get_address(query)
            type = 'Address Info'
        except APIException as e:
            print('Error ' + str(e))
    else:
        type = 'Block Height Info'
        try:
            try:
                n = int(query)
                search_results = be.get_block_height(n, api_code=app.api_code)
            except (ValueError, TypeError) as err:
                search_results = str('Invalid query expression. ' + str(err))
                flash(search_results, 'danger')
                return redirect(url_for('index'))
        except APIException as e:
            print('Error ' + str(e))

    return render_template('results.html',
                           query=query,
                           search_results=search_results,
                           type=type,
                           current_time=datetime.now().strftime('LLL'))
Ejemplo n.º 9
0
def main():

    # get latest block (max height)
    latest_block = be.get_latest_block()
    print("Latest height: ",str(latest_block.height))
    print("Latest hash: ",latest_block.hash)


    # hash of the block where laszlo transaction resides
    pizza_block_hash = "00000000152340ca42227603908689183edc47355204e7aca59383b0aaac1fd8"

    # hash of the laszlo tx
    pizza_tx_hash = "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d"

    # get the block
    pizza_block = be.get_block(pizza_block_hash)
    print("The block height for the Laszlo tx ", pizza_block.height)
    
    # get the tx
    pizza_tx = be.get_tx(pizza_tx_hash)
    print("That pizza cost ", satoshis_to_btc(pizza_tx.outputs.pop().value), " BTCs!")

    # get Txs in Laszlo's address
    laszlo_addr = "1XPTgDRhN8RFnzniWCddobD9iKZatrvH4"
    print("Laszlo transaction list for address ", laszlo_addr)
    laszlo_txs = be.get_address(laszlo_addr).transactions
    for t in laszlo_txs:
        for o in t.outputs:
            print(satoshis_to_btc(o.value))
Ejemplo n.º 10
0
def update():
    """
    Checks/updates pending receiving addresses and checks/updates pending transactions
    """
    # Check all pending receivers
    pending_receivers = db.session.query(Node).filter(Node.role=='receiving',
                                                      Node.status=='pending').all()

    logger.info("pending receivers: "+str(len(pending_receivers)))
    for node in pending_receivers:
        # update the balance from bc.info
        logger.info("checking "+str(node.address))
        bc_address = blockchain.get_address(node.address, confirmations=2)

        node.balance = float(float(bc_address.balance) / float(100000000)) # satoshis -> BTC

        logger.info(str(node.address)+" has "+str(node.balance))
        
        if node.balance >= node.pending_amt:
            # get the origin of the receiver's balance
            origins = []
            node_bc_addr = blockexplorer.get_address(node.address)
            for tx in node_bc_addr.transactions:
                for inpt in tx.inputs:
                    logger.info("appending origin: "+str(inpt.address))
                    origins.append(inpt.address)

            if len(origins) > 1:
                logger.warn("change origin from db string to list!")

            origin_addr = origins[0]
            node.orign = origin_addr
                    
            # inputs have been received, so update its transaction and blunderbuss
            # tag wallet with the origin of its inputs
            tx = db.session.query(Tx).filter(Tx.parent==node.address).one()
            tx.received_inputs = True
            tx.origin = origin_addr
            blunderbussed = controller.blunderbuss(parent=node.address,
                                                   amount=tx.amount,
                                                   origin=origin_addr)
            if blunderbussed:
                node.status='blunderbussed'
                logger.info("blunderbussed")
        db.session.commit()

    # Check all pending txs whose received inputs = True
    pending_txs = db.session.query(Tx).filter(Tx.received_inputs==True,
                                              Tx.outputs_sent==False).all()
    
    logger.info(str(len(pending_txs))+" pending transactions")
    for tx in pending_txs:
        sent = controller.focus_cloud(destination=tx.destination,
                                      amount=tx.amount,
                                      exclude_parents=[tx.parent,tx.origin])
        if sent:
            tx.outputs_sent = True
            logger.info("tx sent")
            
        db.session.commit()
Ejemplo n.º 11
0
def enviado(filename):  #function to see sent volume
    addr = loadfile(filename)
    tt_sent = 0.
    for address in addr:
        addr_stats = blockexplorer.get_address(address)
        tt_sent += addr_stats.total_sent * 10**(-8)
        #print balance
    return round(tt_sent, 8)
Ejemplo n.º 12
0
 def check_for_update(self, last_tx_time_old, address):
     api_address = blockexplorer.get_address(address)
     api_transactions = api_address.transactions
     last_tx_time = api_transactions[1].time
     if last_tx_time_old < last_tx_time:
         return True
     else:
         return False
Ejemplo n.º 13
0
def saldo(filename):  # fuction to see balance of N addresses
    addr = loadfile(filename)
    balance = 0.
    for address in addr:
        addr_stats = blockexplorer.get_address(address)
        balance += addr_stats.final_balance * 10**(-8)
        #print balance
    return round(balance, 8)
Ejemplo n.º 14
0
 def __traverse(self, address):
     try:
         node = blockexplorer.get_address(str(address))
         next = set([
             output.address for transaction in node.transactions
             for output in transaction.outputs
         ])
         print('test')
         return node.transactions, next
     except blockchain.exceptions.APIException:
         return None, set()
Ejemplo n.º 15
0
def get_address(address):
    try:
        addr = be.get_address(address, api_code=app.api_code)
        tx = addr.transactions
    except APIException as e:
        print('Error ' + str(e))

    return render_template('address.html',
                           addr=addr,
                           tx=tx,
                           current_time=datetime.now().strftime('LLL'))
Ejemplo n.º 16
0
 def check_for_update(self):
     api_address = blockexplorer.get_address(self.address)
     api_transactions = api_address.transactions
     if self.n_tx < api_address.n_tx:
         self.total_received = api_address.total_received
         self.total_sent = api_address.total_sent
         self.balance = api_address.final_balance
         self.n_tx = api_address.n_tx
         self.last_tx_date = api_transactions[0].time
         return True
     else:
         return False
Ejemplo n.º 17
0
def get_bitcoin_wallet():
    address = blockexplorer.get_address(e1.get())
    var.set(address.final_balance)
    resultlabel.set("Current Balance:")
    hashlabel.set("Transaction History:")
    stringer = ''
    transactions = address.transactions
    for trans in transactions:
        timestamp = trans.time
        fixedtime = datetime.datetime.fromtimestamp(timestamp)
        fixer = fixedtime.strftime('%Y-%m-%d %H:%M:%S')
        stringer = stringer + "hash: " + trans.hash + "\ntime: " + fixer + "\nip relay: " + str(trans.relayed_by) + "\n"
    hashlist.set(stringer)
Ejemplo n.º 18
0
def transactions(addr):
    address = blockexplorer.get_address(addr)

    transactionsAll = []

    print("TRANSACTIONS of " + str(addr))

    for trans in address.transactions:

        #(input,output) = listInOut(trans.hash)
        transactionsAll.append(trans)

    return transactionsAll[::-1]
Ejemplo n.º 19
0
 def blockexplorer(self):
     block = blockexplorer.get_block(
         '000000000000000016f9a2c3e0f4c1245ff24856a79c34806969f5084f410680')
     tx = blockexplorer.get_tx(
         'd4af240386cdacab4ca666d178afc88280b620ae308ae8d2585e9ab8fc664a94')
     blocks = blockexplorer.get_block_height(2570)
     address = blockexplorer.get_address(
         '1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd')
     xpub = None  #blockexplorer.get_xpub('xpub6CmZamQcHw2TPtbGmJNEvRgfhLwitarvzFn3fBYEEkFTqztus7W7CNbf48Kxuj1bRRBmZPzQocB6qar9ay6buVkQk73ftKE1z4tt9cPHWRn')
     addresses = None  # blockexplorer.get_multi_address('1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd', 'xpub6CmZamQcHw2TPtbGmJNEvRgfhLwitarvzFn3fBYEEkFTqztus7W7CNbf48Kxuj1bRRBmZPzQocB6qar9ay6buVkQk73ftKE1z4tt9cPHWRn')
     outs = blockexplorer.get_unspent_outputs(
         '1HS9RLmKvJ7D1ZYgfPExJZQZA1DMU3DEVd')
     latest_block = blockexplorer.get_latest_block()
     txs = blockexplorer.get_unconfirmed_tx()
     blocks_by_name = None  #blockexplorer.get_blocks(pool_name = 'Discus Fish')
Ejemplo n.º 20
0
 def get(self, address, request):
     '''
     @return
         hash160 : str
         address : str
         n_tx : int
         total_received : int
         total_sent : int
         final_balance : int
         transactions : array of Transaction objects
     '''
     from blockchain import blockexplorer
     address_data = blockexplorer.get_address(address)
     content = {'data': address_data}
     return Response(content)
Ejemplo n.º 21
0
def buildSankey(exploredAddresses, edge_factory, edges, address):
	# print 'explored:', exploredAddresses
	# print 'address:', address
	address_string = address
	address_object = blockexplorer.get_address(address_string)
	transactions = address_object.transactions
	unexploredAddresses = {}
	for t in transactions:
		inputs = t.inputs
		outputs = t.outputs
		createLeavingEdges(exploredAddresses, unexploredAddresses, edge_factory, edges, address_string, inputs, outputs)
		createIncomingEdges(exploredAddresses, unexploredAddresses, edge_factory, edges,address_string,inputs,outputs)

	exploredAddresses.add(address_string)
	result = printSankeyInfo(edge_factory, edges)
	return result, exploredAddresses
Ejemplo n.º 22
0
def getSankey(address):
	unexploredAddresses = {}
	exploredAddresses = set()
	edges = []
	edge_factory = EdgeFactory()

	# address_string = popUnexploredAddress(unexploredAddresses)
	address_string = address
	address_object = blockexplorer.get_address(address_string)
	transactions = address_object.transactions
	for t in transactions:
		inputs = t.inputs
		outputs = t.outputs
		createLeavingEdges(exploredAddresses, unexploredAddresses, edge_factory, edges, address_string, inputs, outputs)
		createIncomingEdges(exploredAddresses, unexploredAddresses, edge_factory, edges, address_string, inputs, outputs)

	exploredAddresses.add(address_string)
	result = printSankeyInfo(edge_factory, edges)
	return result, exploredAddresses
def get_utxo_set(address: str, testnet: bool = False) -> List[str]:
    """
    Retrieves UTXO (unspent transaction outputs) for a given address
    This is used to determine output amounts and fees.
    UTXOs are pulled from online block explorers

    Args:
        address: bitcoin address in Base58Check encoding (standard address format)
        testnet: Is the address on testnet or mainnet?

    Returns:
        List of Output Dict objects with txid, n, and amount keys

    Example:
        TODO
    """

    if testnet:
        util.BASE_URL = "https://testnet.blockchain.info/"
    else:
        util.BASE_URL = "https://blockchain.info/"

    transactions = BlockExplorer.get_address(address).transactions
    utxos = []
    for tx in transactions:
        for utxo in tx.outputs:
            if not utxo.spent and utxo.address == address:
                utxos.append({"txid": tx.hash, "n": utxo.n, "amount":utxo.value})


    for utxo in utxos:
        url = util.BASE_URL + "tx/" + utxo['txid'] + "?format=hex"
        res = requests.get(url=url)
        utxo['rawRefTx'] = res.content.decode()
        
    return utxos
Ejemplo n.º 24
0
def extractTransactionLists(ownAddress):
    TxReceivedList = []
    TxSentList = []

    transactionList = []
    stepsize = 50
    address = blockexplorer.get_address(ownAddress, limit=stepsize)
    nTx = address.n_tx

    for i in range(0, nTx, stepsize):
        print(i)
        address = blockexplorer.get_address(ownAddress,
                                            limit=stepsize,
                                            offset=i)
        transactionList += address.transactions

    print("No. Tx: " + str(address.n_tx))
    print("len: " + str(len(transactionList)))
    finalBalance = 0
    totalSent = 0
    totalReceived = 0

    for tx in transactionList:
        date = datetime.datetime.fromtimestamp(tx.time)
        dateFormatted = date.strftime('%Y-%m-%d %H:%M:%S')
        print(dateFormatted)
        print(tx.hash)
        print("inputs")
        txVal = 0
        for input in tx.inputs:
            print(str(input.address) + " | value: " + str(input.value))

            if str(input.address) == ownAddress:
                txVal -= input.value

        print("outputs")
        for output in tx.outputs:
            print(
                str(output.address) + " | value: " + str(output.value) +
                " | " + str(output.spent))

            if str(output.address) == ownAddress:
                txVal += output.value

        if (txVal < 0):
            totalSent -= txVal  #negative
            TxSentList.append(TxSent(date, txVal))
        else:
            totalReceived += txVal  #positive
            TxReceivedList.append(TxReceived(date, txVal))

        print("txVal: " + str(txVal)
              )  # if negative: sent |txVal|, if positive: received |txVal|
        finalBalance += txVal

        print("#################################################")

    if (address.total_received == totalReceived
            and address.total_sent == totalSent
            and address.final_balance == finalBalance):
        print("OK!")
    else:
        print("ERROR!")

    TxReceivedList.reverse()
    TxSentList.reverse()

    return TxReceivedList, TxSentList
Ejemplo n.º 25
0
#!/usr/bin/python3
# Author: James Campbell
# Date: November 22 2015
# What: Accesses the blockchain module and queries some data as example
import sys
from sys import exit
import datetime
from blockchain import blockexplorer
# example address test
address = blockexplorer.get_address('1SDude3hVWoAT2sFxy3JkH2VrcUXPM4PA')
if len(sys.argv) > 1:  # you can pass a bitcoin address in from terminal
    print(sys.argv[1])
    address = blockexplorer.get_address(sys.argv[1])
    print(address)
# final balance
print(address.final_balance)  # add decimal after first
transactions = address.transactions
for trans in transactions:
    print(trans.relayed_by)  # print ip address of the relayed transaction
    print(trans.hash)  # hash of the transaction
    print(trans.time)  # time of the transaction
    timestamp = trans.time
    fixedtime = datetime.datetime.fromtimestamp(timestamp)
    fixer = fixedtime.strftime('%Y-%m-%d %H:%M:%S')
    print('Converted time:', fixedtime.strftime('%Y-%m-%d %H:%M:%S'))
    # inventory only works for transactions up to 1 hour old
    # inv = blockexplorere.get_inventory_data(trans.hash)
    # print('Time: %s Initial IP: %s' % (fixer, inv.initial_ip))
exit()
Ejemplo n.º 26
0
### Importing modules for Blockchain Interaction, Referance: https://github.com/blockchain/api-v1-client-python
from blockchain import blockexplorer
from blockchain import statistics


### Gaining access to 1 google spreadsheet, in this case name = "BTC"
json_key = json.load(open('gspreadtest-2f9b2a153d04.json'))
scope = ['https://spreadsheets.google.com/feeds']

credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)

btc = gc.open("BTC").sheet1


### Pulling data from Bitcoin Blockchain
address = blockexplorer.get_address('16RyYkFi7fkqFD9KP6NdYcSsZj77EHABaf')

### Putting data onto Google Spreadhseets
### btc.update_acell('A2', address.final_balance )
print address.total_received

for x in address.transactions:
	pos = address.transactions.index(x)
	btc.update_acell('A' + str(pos + 1), address.transactions[pos].outputs[0].value)
	print x.outputs[0].value



Ejemplo n.º 27
0
# Coinbase
# root_address = '17bWK1kGySckEV7jpNBHUmHuX1UoHeHoAs'
# Circle
# root_address = '1LZpJP5zKGAXnH4SnJF98cVn7sBHJroViG'
# Multibit to Circle
# root_address = '1DJv4wgJXCwK4m2BEmjg5P4meYKhKtcp9K'
# Circle Afterwards
root_address = '1PyZX9JTfs3vgnN2MRJTk9rH2f7aG7ukoR'
unexploredAddresses[root_address] = 1

# Explore an address, create edges in/out of this address
for i in range(4):
	address_string = popUnexploredAddress(unexploredAddresses)

	address_object = blockexplorer.get_address(address_string)

	transactions = address_object.transactions
	for t in transactions:
		inputs = t.inputs
		outputs = t.outputs
		createLeavingEdges(exploredAddresses, unexploredAddresses, edge_factory, edges, address_string, inputs, outputs)
		createIncomingEdges(exploredAddresses, unexploredAddresses, edge_factory, edges,address_string,inputs,outputs)

	exploredAddresses.add(address_string)

	


# Create input string for Sankey diagram given edges and edge_factory
node_list_result = ''
Ejemplo n.º 28
0
                input_index = i

        # Traverse blockchain to update lock ownership if credentials are outdated
        if input_index == -1:
            try:
                utxo = blockexplorer.get_unspent_outputs(self.public_address)
                tx_hashes  = [str(i.tx_hash) for i in utxo]
                if any(self.transaction in tx_hashes):
                    return 'Not Updated'
                else:
                    self.updateLock(1)                
            except blockchain.exceptions.APIException:
                response = 'go'
                j = 0
                while response == 'go':
                    old_address = blockexplorer.get_address(self.public_address)
                    outputs = old_address.transactions[0].outputs
                    scripts = [str(i.script) for i in outputs]   
                    num_inputs = len(old_address.transactions[0].inputs)
                    output_index = self.ProcessTransaction(scripts, True,num_inputs)
                    if output_index is None:
                        output_index = 0
                    else:
                        output_index = int(output_index)
                    last_trans_output = old_address.transactions[0].outputs[output_index]
                
                    included_block = old_address.transactions[0].block_height
                    latest_block = blockexplorer.get_latest_block()
                    if (latest_block.height - included_block < 3):
                        if j == 0:
                            return 'Not Updated because of lack of confidence'
Ejemplo n.º 29
0
def wallet():
    address = blockexplorer.get_address('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
    return render_template('wallet', address=address)
Ejemplo n.º 30
0
def user_crypto_balance(request):
    user = MyUser.objects.get(username=request.user.username)
    btc_user_info = blockexplorer.get_address(user.crypto_wallet)
    btc_balance = btc_user_info.final_balance / 100000000
    return btc_balance
Ejemplo n.º 31
0
    def updateLock(self, num):
        """ Checks and updates lock if ownernship has changed 

        :return: Result of checking and updating lock ownership
        """
        try:
            utxo = blockexplorer.get_unspent_outputs(self.public_address)
            tx_hashes  = [str(i.tx_hash) for i in utxo]
            if any(self.transaction in tx_hashes):
                return 'Not Updated'
            else:
                response = 'go'
                j = 0
                while response == 'go':
                    old_address = blockexplorer.get_address(self.public_address)
                    outputs = old_address.transactions[0].outputs
                    scripts = [str(i.script) for i in outputs]   
                    num_inputs = len(old_address.transactions[0].inputs)
                    output_index = self.ProcessTransaction(scripts, True,num_inputs)
                    if output_index is None:
                        output_index = 0
                    else:
                        output_index = int(output_index)
                    last_trans_output = old_address.transactions[0].outputs[output_index]
                    
                    included_block = old_address.transactions[0].block_height
                    latest_block = blockexplorer.get_latest_block()
                    if (latest_block.height - included_block < 3):
                        if j == 0:
                            return 'Not Updated because of lack of confidence'
                        if j > 0:
                            if trans == str(old_address.transaction[0].hash):
                                return 'Not enough confidence in provided transaction (updated to new address though)'
                            else:
                                return 'Not enough confidence but not in the provided transaction (updated to new address though)'
                    self.public_address = str(last_trans_output.address)
                    self.transaction = str(old_address.transactions[0].hash)
                    try:
                        utxo_2 = blockexplorer.get_unspent_outputs(self.public_address)
                        tx_hashes_2s = [str(i.tx_hash) for i in utxo_2]
                        if any(self.transaction in tx_hashes_2):
                            reponse = 'exit'
                    except blockchain.exceptions.APIException:
                        j = j + 1

                    f = open('lock.txt','w')
                    f.write(self.transaction)
                    f.write('\n')
                    f.write(self.public_address)
                    f.close()
                    return 'Updated but not with transaction provided'

        except blockchain.exceptions.APIException:
            response = 'go'
            j = 0
            while response == 'go':
                old_address = blockexplorer.get_address(self.public_address)
                outputs = old_address.transactions[0].outputs
                scripts = [str(i.script) for i in outputs]   
                num_inputs = len(old_address.transactions[0].inputs)
                output_index = self.ProcessTransaction(scripts, True,num_inputs)
                if output_index is None:
                    output_index = 0
                else:
                    output_index = int(output_index)
                last_trans_output = old_address.transactions[0].outputs[output_index]
                
                included_block = old_address.transactions[0].block_height
                latest_block = blockexplorer.get_latest_block()
                if (latest_block.height - included_block < 3):
                    if j == 0:
                        return 'Not Updated because of lack of confidence'
                    if j > 0:
                        if trans == str(old_address.transaction[0].hash):
                            return 'Not enough confidence in provided transaction (updated to new address though)'
                        else:
                            return 'Not enough confidence but not in the provided transaction (updated to new address though)'
                self.public_address = str(last_trans_output.address)
                self.transaction = str(old_address.transactions[0].hash)
                try:
                    blockexplorer.get_unspent_outputs(self.public_address)
                    reponse = 'exit'
                except blockchain.exceptions.APIException:
                    j = j + 1

                f = open('lock.txt','w')
                f.write(self.transaction)
                f.write('\n')
                f.write(self.public_address)
                f.close()
                return 'Updated but not with transaction provided'
Ejemplo n.º 32
0
 def get_users():
     whales_address = list()
     for u in __class__.top_10:
         whales_address.append(blockexplorer.get_address(u))
     return whales_address
Ejemplo n.º 33
0
def balance(address):  # fuction to see balance for 1 address
    address_stats = blockexplorer.get_address(address)
    balance = float(address_stats.final_balance) * 10**(-8)
    return round(balance, 8)
Ejemplo n.º 34
0
# Coinbase
# root_address = '17bWK1kGySckEV7jpNBHUmHuX1UoHeHoAs'
# Circle
# root_address = '1LZpJP5zKGAXnH4SnJF98cVn7sBHJroViG'
# Multibit to Circle
# root_address = '1DJv4wgJXCwK4m2BEmjg5P4meYKhKtcp9K'
# Circle Afterwards
root_address = '1PyZX9JTfs3vgnN2MRJTk9rH2f7aG7ukoR'
unexploredAddresses[root_address] = 1

# Explore an address, create edges in/out of this address
for i in range(4):
    address_string = popUnexploredAddress(unexploredAddresses)

    address_object = blockexplorer.get_address(address_string)

    transactions = address_object.transactions
    for t in transactions:
        inputs = t.inputs
        outputs = t.outputs
        createLeavingEdges(exploredAddresses, unexploredAddresses,
                           edge_factory, edges, address_string, inputs,
                           outputs)
        createIncomingEdges(exploredAddresses, unexploredAddresses,
                            edge_factory, edges, address_string, inputs,
                            outputs)

    exploredAddresses.add(address_string)

# Create input string for Sankey diagram given edges and edge_factory
Ejemplo n.º 35
0
def checkbalance():
    val = blockexplorer.get_address(add)
    realval = float(val.final_balance) / 100000000
    return realval
Ejemplo n.º 36
0
    def post(self, request):
        '''Takes given address and validates.
        If address is not in base - saves it create new Address object and saves all transactions.
        Creates QRcode and returns template.
        If address is in base - checks if all transactions are in base and returns template.
        If some transactions are missing deletes object from base and creates new one with all transactions.
        '''
        form = AddressForm(request.POST)
        if form.is_valid():
            form_address = form.cleaned_data['address']
            start_date = form.cleaned_data['start_date']
            end_date = form.cleaned_data['end_date']
            api_address = blockexplorer.get_address(form_address)
            base_address = TransactionView.get_object(form_address)
            img = pyqrcode.create(form_address)
            img.png('bc_app/static/QRcode.png', scale=3)
            
            if base_address:

                if len(base_address.transactions.all()) == len(api_address.transactions):

                    transactions = TransactionView.transaction_search(base_address, start_date, end_date)
                    return render(request, template_name='base.html', context={'address': base_address,
                                                                               'form': form,
                                                                               'start_date': start_date,
                                                                               'end_date': end_date,
                                                                               'transactions': transactions})
                else:
                    base_address.delete()

            base_address = Address.objects.create(
                address=api_address.address,
                hash160=api_address.hash160,
                final_balance=api_address.final_balance,
                n_tx=api_address.n_tx,
                total_received=api_address.total_received,
                total_sent=api_address.total_sent
            )

            for transaction in api_address.transactions:

                inputs_str = json.dumps(transaction.inputs, default=lambda o: o.__dict__)
                inputs_data = json.loads(inputs_str)

                outputs_str = json.dumps(transaction.outputs, default=lambda o: o.__dict__)
                outputs_data = json.loads(outputs_str)

                Transaction.objects.create(
                    block_height=transaction.block_height,
                    double_spend=transaction.double_spend,
                    hash=transaction.hash,
                    relayed_by=transaction.relayed_by,
                    size=transaction.size,
                    time=transaction.time,
                    tx_index=transaction.tx_index,
                    version=transaction.version,
                    inputs=inputs_data,
                    outputs=outputs_data,
                    address=base_address
                )

            transactions = TransactionView.transaction_search(base_address, start_date, end_date)
            return render(request, template_name='base.html', context={'address': base_address,
                                                                       'form': form,
                                                                       'start_date': start_date,
                                                                       'end_date': end_date,
                                                                       'transactions': transactions})

        return render(request, template_name='base.html', context={'form': form})
Ejemplo n.º 37
0
#!/usr/bin/python3
import time
import CryptographyFunctions
from blockchain import blockexplorer
# maybe try with websockets later on // https://www.blockchain.com/api/api_websocket
# my wallet actual address
botmasterAddress = '1GgH68gphSF1JHASKa7goET23sHwPqLJFD'
# a test address
botmasterAddress = '3Nzz16cQdmKDmPkNtsjpUP5uqCwg4i4wN7'
keyForSubliminalDecryption = ''

# get the list of Bot master trxs
EncodedTransactionsList = blockexplorer.get_address(
    botmasterAddress).transactions
transactionsFromMaster = len(EncodedTransactionsList)
print("1st -- transactionsFromMaster -- : ", transactionsFromMaster)
DecodedTransactionsList = []

# this command returns the first transaction as shown in the website
# print("block is --> ",  address.transactions[0])
# inputs is an array of people who contributed in this trx
# outputs is an array of people who received money from this trx
# print("block is --> ",  address.transactions[0].inputs[0].address)
# print("block is --> ", EncodedTransactionsList[0].hash)

# for the thesis we may need to check only unconfirmed trxs of botmaster

# 1. try getting new transactions generated by the bot master
# 2. store them in a list
# 3. try decoding them (
#   if success :
Ejemplo n.º 38
0
#!/usr/bin/python3
# Author: James Campbell
# Date: 2015-11-22
# Date Updated: 2019-06-19
# What: Accesses the blockchain module and queries some data as example
import sys
from sys import exit
import datetime
from blockchain import blockexplorer

# example address test
address = blockexplorer.get_address("1SDude3hVWoAT2sFxy3JkH2VrcUXPM4PA")
if len(sys.argv) > 1:  # you can pass a bitcoin address in from terminal
    print(sys.argv[1])
    address = blockexplorer.get_address(sys.argv[1])
    print(address)
# final balance
print(f"\nFinal balance of wallet: {address.final_balance}"
      )  # add decimal after first
transactions = address.transactions
print(
    f"\nList of {len(transactions)} transactions: \n -----------------------------"
)
for trans in transactions:
    print(f"Ip address of relayed transaction: {trans.relayed_by}"
          )  # print ip address of the relayed transaction
    print(f"Hash of the transaction: {trans.hash}")  # hash of the transaction
    print(f"Time of the transaction: {trans.time}")  # time of the transaction
    timestamp = trans.time
    fixedtime = datetime.datetime.fromtimestamp(timestamp)
    fixer = fixedtime.strftime("%Y-%m-%d %H:%M:%S")
Ejemplo n.º 39
0
def get_wallet_amount(wallet):
    return sat_to_btc(get_address(wallet).total_received)