Esempio n. 1
0
    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'
Esempio n. 2
0
    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'
Esempio n. 3
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))
Esempio n. 4
0
 def transact(self, flightid, offerid, txn_id):
     """Run a transaction. Doing this requires the following to happen:
     1. Validate the offer pending
     2. Check that the txn_id is indeed present in the blockchain (txn has taken place)
     3. Remove the offer from the offer list
     4. Invalidate all other offers for the "to" user (since they've moved seats now)
     5. Switch seats
     6. Update state changed
     """
     searched = self.flights.find_one({'_id': flightid})
     if searched:
         # Validate offer. Remember offers are unique (or at least are supposed to be)
         offer = self.get_offer(flightid, offerid)
         if 'error' in offer:
             return offer
         # Check that the transaction has happened
         try:
             block = blockexplorer.get_tx(txn_id)
         except APIException as e:
             return {'error': 'Bitcoin transaction not found'}
         # Remove offer from the list. We're gonna (unwisely) assume this works with no problems
         self.delete_offer(flightid, offerid)
         # Invalidate other offers.
         tooffers = self._invalidate_offers(flightid, offer['to'])
         fromoffers = self._invalidate_offers(flightid, offer['fr'])
         if not tooffers and not fromoffers:
             return {'Failed to invalidate outstanding transactions'}
         # Actually switch the seats
         passenger1 = self.get_passenger(flightid, offer['to'])
         passenger2 = self.get_passenger(flightid, offer['fr'])
         self._swap_seats(flightid, passenger1, passenger2)
         # Update state change. Not sure how we're gonna do that one....
         return {'success': 'Transaction completed (txn {})'.format(txn_id)}
     else:
         return {'error': 'Could not find flight'}
Esempio n. 5
0
def main():
    latest_block = be.get_latest_block()
    print("latest block:", latest_block.height)
    print("latest block hash", latest_block.hash)
    
    pizza_tx_hash = "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d"
    pizza_block_hash = "00000000152340ca42227603908689183edc47355204e7aca59383b0aaac1fd8"
    laszlo_addr = "1XPTgDRhN8RFnzniWCddobD9iKZatrvH4"

    pizza_block = be.get_block(pizza_block_hash)
    print("The block height for the Laszlo tx is ", pizza_block.height)

    pizza_tx = be.get_tx(pizza_tx_hash)

    print(pizza_tx)

    for o in pizza_tx.outputs:
        print(satoshi_to_btc(o.value))
    
    s = 0
    for o in pizza_tx.inputs:
        s += satoshi_to_btc(o.value)
        print(satoshi_to_btc(o.value))

    pizza_cost = format(satoshi_to_btc(pizza_tx.outputs.pop().value), ",f")
    print("The cost of the pizza was", pizza_cost)
def listInOut(txHash):
    tx = blockexplorer.get_tx(txHash)
    print("TxHash: " + txHash)
    print("TIME: " + str(tx.time))

    print(str("INPUTS: " + str(len(tx.inputs))))

    totalIN = 0
    for i in range(len(tx.inputs)):

        try:
            print(tx.inputs[i].address + ": " +
                  str(tx.inputs[i].value / 100000000))
            totalIN += tx.inputs[i].value
        except:
            print("Coinbase transaction ")
            #totalIN+=tx.inputs[i].value
    #print("total IN: "+str(totalIN/100000000))
    print()

    print(str("OUTPUTS: " + str(len(tx.outputs))))

    totalOUT = 0
    for i in range(len(tx.outputs)):
        spent = tx.outputs[i].spent
        print(tx.outputs[i].address + ": " +
              str(tx.outputs[i].value / 100000000) + " | spent: " + str(spent))
        totalOUT += tx.outputs[i].value
        #print(tx.outputs[i].n)
    print("total: " + str(totalOUT / 100000000) + " BTC")

    print("-------------------------------")
    return (tx.inputs, tx.outputs)
Esempio n. 7
0
def check_unprocessed(top_height):
    for tx_hash in unprocessed_txs.members():
        txid = hash_to_hex(tx_hash).decode()
        tx = Tx.tx_from_hex(txs[tx_hash].decode())
        tx_blockchain = get_tx(txid)
        logging.info('Checking %s' % txid)
        if tx_blockchain.block_height == -1:
            continue
        if top_height - tx_blockchain.block_height + 1 >= REQUIRED_CONFIRMATIONS:  # off by one error - if tx in top block that is 1 conf
            unprocessed_txs.remove(tx_hash)
            for out in tx.txs_out:
                address = out.bitcoin_address()
                if address not in all_addresses:
                    continue
                account = Account(addr_to_uid[address])
                satoshis = out.coin_value
                satoshis = int(satoshis / (1 + account.tip.get()))  # scale for tip
                account.total_coins.incr(satoshis)
                node_minutes_d = calc_node_minutes(satoshis, exchange_rate=exchange_rate.get())
                account.total_minutes.incr(node_minutes_d)
                total_nodeminutes.incr(node_minutes_d)
                nodes_recently_updated.append(account.uid)
                account.add_msg('Detected payment via txid: %s' % (txid,))
                account.add_msg('Increased total paid by %.8f to %.8f (considering tip of %d %%)' % (satoshis / COIN, account.total_coins.get() / COIN, account.tip.get() * 100))
                account.add_msg('Increased node life by %d minutes; expiring around %s' % (node_minutes_d, account.get_expiry().isoformat()))
def searchFutureOfTransaction(txHash, percent):

    #print("TEEEEEESTEEEEEE")
    tx = blockexplorer.get_tx(txHash)

    OUTPUTLIST = tx.outputs

    print(len(OUTPUTLIST))

    valueOut = 0

    for OUTPUT in OUTPUTLIST:
        valueOut += OUTPUT.value

    #mutex = Lock()

    global finalTable

    for OUTPUT in OUTPUTLIST:

        print(OUTPUT.spent)

        if not OUTPUT.spent:

            #mutex.acquire()
            finalTable.append((OUTPUT.address, OUTPUT.value / 100000000,
                               percent * OUTPUT.value / valueOut * 100))
            #mutex.release()
            print(finalTable)
            print("utxo added")

        else:

            transactionList = transactions(OUTPUT.address)

            for trans in transactionList:
                (inputlist, outputlist) = listInOut(trans.hash)

                valueIn = 0
                for inp in inputlist:
                    valueIn += inp.value

                ratio = 1
                for inp in inputlist:

                    if trans.time > tx.time and inp.address == OUTPUT.address:

                        if valueIn > OUTPUT.value:
                            print("new inputs added!!!")
                        ratio = inp.value / valueIn

                        #print("PERCENT: "+str(percent*inp.value/valueIn*100)+"%")
                        searchFutureOfTransaction(
                            trans.hash,
                            ratio * percent * OUTPUT.value / valueOut)
                        break

                    #break
                valueIn = 0
Esempio n. 9
0
    def old_tx(self, txid, vout):
        # Get the previous transaction

        # Go to old transaction
        tx_old = blockexplorer.get_tx(txid)

        # Find the correct output
        return tx_old.outputs[vout]
Esempio n. 10
0
def get_tx_info(tx_hash):
    try:
        tx = blockexplorer.get_tx(tx_hash)
    except socket.timeout:
        print("Blockchain API limit exceeded. Waiting for 5 seconds")
        sleep(5)
        tx = get_tx_info(tx_hash)
    # Return tx information
    return tx
Esempio n. 11
0
def decode_tx(bytes_):
    readable = deserialize(bytes_)
    inputs_decoded = [{
        'address':
        blockexplorer.get_tx(
            i['outpoint']['hash']).outputs[i['outpoint']['index']].address,
        'value':
        blockexplorer.get_tx(
            i['outpoint']['hash']).outputs[i['outpoint']['index']].value,
        'prev_hash':
        i['outpoint']['hash'],
        'index':
        i['outpoint']['index'],
        'script':
        i['script'],
        'sequence':
        i['sequence']
    } for i in readable['ins']]
    outputs_decoded = [{
        'address': hex_to_b58check(i['script'][6:-4]),
        'value': i['value'],
        'script': i['script']
    } for i in readable['outs']]
    all_addresses = list(
        set([i['address'] for i in inputs_decoded] +
            [j['address'] for j in outputs_decoded]))
    full_decode = {
        'addresses':
        all_addresses,
        'version':
        readable['version'],
        'size':
        len(bytes_) / 2,
        'fees':
        sum([i['value'] for i in inputs_decoded]) -
        sum([i['value'] for i in outputs_decoded]),
        'locktime':
        readable['locktime'],
        'inputs':
        inputs_decoded,
        'outputs':
        outputs_decoded
    }
    return full_decode
Esempio n. 12
0
def tx(hash):
    try:
        tx = be.get_tx(hash, api_code=app.api_code)
        blk = be.get_block_height(tx.block_height, api_code=app.api_code)
    except APIException as e:
        message = 'There has been an API Error.'
        flash(message, 'danger')
        return redirect(url_for('index'))

    return render_template('transaction.html',
                           tx=tx,
                           block=blk,
                           current_time=datetime.now().strftime('LLL'))
Esempio n. 13
0
    def changeOwnership(self, trans):
        """ Change the address associated with the ownernship of this lock

        :param Valid transaction proving ownership changeOwnership
        :return: String stating outcome of attempted ownership change
        """

        newTransaction = 0

        # Check to see if transaction is valid and conerns this lock
        try:
            newTransaction = blockexplorer.get_tx(trans)
        except blockchain.exceptions.APIException, TypeError:
            return 'Invalid transaction'
Esempio n. 14
0
    def changeOwnership(self,trans):
        """ Change the address associated with the ownernship of this lock

        :param Valid transaction proving ownership changeOwnership
        :return: String stating outcome of attempted ownership change
        """

        newTransaction = 0
        
        # Check to see if transaction is valid and conerns this lock
        try: 
            newTransaction = blockexplorer.get_tx(trans)
        except blockchain.exceptions.APIException, TypeError:
            return 'Invalid transaction'
Esempio n. 15
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')
Esempio n. 16
0
def nextHoop(txHash):
    tx = blockexplorer.get_tx(txHash)

    global finalAddr

    nextAddr = []
    finalAddr = []

    for out in tx.outputs:
        if out.spent:
            nextAddr.append((out, tx.time))
            print("Next Hoop: " + out.address)
        else:
            finalAddr.append(out)

    return nextAddr, finalAddr
Esempio n. 17
0
        def add_unfiltered():
            get_addrs_for = set()

            for nulldata in get_unfiltered():
                self.session.add(FilteredNulldata(nulldata_id=nulldata.id))
                if nulldata_filter(nulldata):
                    self.session.add(RawVote(nulldata_id=nulldata.id))
                    get_addrs_for.add(nulldata)

            self.session.commit()

            for nd in get_addrs_for:
                print('Getting Address for %s' % nd.txid)
                tx = get_tx(tx_id=nd.txid)  # this is REALLY slow, TODO : parallelize like coinsecrets.
                nd.address = find_address_for_nulldata(nd, tx)
                self.session.commit()
                logging.info("Set nd.address of %d to %s" % (nd.id, nd.address))
Esempio n. 18
0
def verify(tx_hash, address):
    try:
        tx = blockexplorer.get_tx(tx_hash, api_code=get_apikey())
    except APIException:
        print("An exception occurred api side. The transaction may not have gone in.")
        return
    except:
        print("An unexpected error occurred.")
        return

    match = False
    for a in tx.outputs:
        if a.address == address:
            match = True
            break

    if not match:
        raise Exception("Transaction address may not have matched")

    return (tx.time, tx.block_height)
Esempio n. 19
0
blocks_heights = range(100)

if not os.path.isfile('./cash_flows.pkl'):
    # get blocks and corresponding transaction hash list
    blocks = []
    for block_height in blocks_heights:
        blocks += blockexplorer.get_block_height(block_height)

    transactions_hash_list = []
    for block in blocks:
        transactions_hash_list += [tx.hash for tx in block.transactions]

    # get corresponding transactions data
    transactions = []
    for tx_id in transactions_hash_list:
        transactions.append(blockexplorer.get_tx(tx_id))

    # save corresponding cash flows per user
    cash_flows = []
    for transaction in transactions:
        # get transaction cash flows
        for input_ in transaction.inputs:
            if hasattr(input_, 'address'):
                cash_flows.append(
                    [input_.address, transaction.time, -input_.value])
        for output_ in transaction.outputs:
            if hasattr(output_, 'address'):
                cash_flows.append(
                    [output_.address, transaction.time, +output_.value])

    # converts it to df
from blockchain import blockexplorer, util
import json



latest_block = blockexplorer.get_latest_block()

numberOfTXs = len(latest_block.tx_indexes)


#print numberOfTXs
numberOfInputs = 0
numberOfOutputs = 0
for x in range (0, numberOfTXs):
	txs = blockexplorer.get_tx(str(latest_block.tx_indexes[x]))
	numberOfInputs += len(txs.inputs)
	numberOfOutputs += len(txs.outputs)

print "avg outputs per transactions " + str (numberOfOutputs/numberOfTXs)
print "avg inputs per transactions " + str(numberOfInputs/numberOfTXs)
Esempio n. 21
0
    # Fix: sometimes the latest block is unconfirmed and it's number is 0
    if end_block_nr == 0:
        end_block_nr = start_block_nr + 1000000

    block_keys = ["hash", "gasUsed", "gasLimit", "number", "timestamp"]
    tx_keys = ["hash", "blockHash", "from", "to", "value", "gas", "gasPrice"]
    ip_keys = ["hash", "relayed_by"]

    for current_block_nr in trange(start_block_nr, end_block_nr + 1):
        try:
            block = w3.eth.getBlock(current_block_nr)
            database.update(block, 'blocks', block_keys)
            database.update_list(block, 'transactions', tx_keys)
            for tx in database.tx_iterator(block):
                try:
                    transaction = blockexplorer.get_tx(tx, api_code=api_code)
                    database.update(transaction, 'ip_info', ip_keys)
                except exceptions.APIException:
                    continue
                except Exception as e:
                    logger.error(e)
                    continue
            # Save progress
            with open("progress.txt", "a") as f:
                f.write(str(current_block_nr) + "\n")
        except UnhandledRequest as error:
            logger.error(error)
            sys.exit(1)

        except (EOFError, KeyboardInterrupt):
            logger.info("Aborting ETL")
Esempio n. 22
0
logging.basicConfig(level=logging.INFO)

if __name__ == '__main__':
    while True:
        latest_block = get_latest_block()
        best_block_hash = latest_block.hash
        top_height = latest_block.height
        if best_block_hash == last_block_checked.get():
            time.sleep(10)  # only do this at most once per block
            continue
        logging.info('Latest block: %s' % best_block_hash)

        for tx_hash in unprocessed_txs.members():
            txid = hash_to_hex(tx_hash).decode()
            tx = Tx.tx_from_hex(txs[tx_hash].decode())
            tx_blockchain = get_tx(txid)
            logging.info('Checking %s' % txid)
            if tx_blockchain.block_height == -1:
                continue
            if top_height - tx_blockchain.block_height + 1 >= REQUIRED_CONFIRMATIONS:  # off by one error - if tx in top block that is 1 conf
                unprocessed_txs.remove(tx_hash)
                for out in tx.txs_out:
                    address = out.bitcoin_address()
                    if address not in all_addresses:
                        continue
                    account = Account(addr_to_uid[address])
                    satoshis = out.coin_value
                    satoshis = int(satoshis / (1 + account.tip.get()))  # scale for tip
                    account.total_coins.incr(satoshis)
                    node_minutes_d = calc_node_minutes(satoshis, exchange_rate=exchange_rate.get())
                    account.total_minutes.incr(node_minutes_d)
Esempio n. 23
0
def tx_iterator(block):
    for transaction in block.transactions:
        yield transaction.hex()


if __name__ == "__main__":
    block = w3.eth.getBlock(6753133)
    block_keys = ["hash", "gasUsed", "gasLimit", "number", "timestamp"]
    tx_keys = ["blockHash", "hash", "from", "to", "value", "gas", "gasPrice"]
    ip_keys = ["hash", "relayed_by"]

    update(block, 'blocks', block_keys)
    update_list(block, 'transactions', tx_keys)
    for tx in tx_iterator(block):
        try:
            transaction = blockexplorer.get_tx(tx)
            update(transaction, 'ip_info', ip_keys)
        except Exception as e:
            print(e)
            continue


def query(block):
    with open(os.path.join("sql", "query", "extract_info.sql")) as q:
        sql = q.read()
    conn = None
    try:
        params = config()
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        cur.execute(sql.format(block))
Esempio n. 24
0
    ll.list_print()"""

    global finalTable

    global finalAddr

    finalTable = []

    finalAddr = []
    """for t in trans:
        for out in t:
            print(out.address)"""

    txHash = "0c60ce100b7d4a6a12b767896606d3e777243cac54d7cc539d277aae57e5cd76"

    tx = blockexplorer.get_tx(txHash)

    OUTPUTLIST = tx.outputs

    valueOut = 0

    for OUTPUT in OUTPUTLIST:
        valueOut += OUTPUT.value

    #print(finalTable)

    searchFutureOfTransaction(txHash, 1)

    total = 0
    percent = 0
Esempio n. 25
0
print(wallet.get_balance())


# This will print the addresses in the wallet

addresses = wallet.list_addresses()
for a in addresses:
    print(a.balance)

# This will show the balance of a given address
addr = wallet.get_address('1NAF7GbdyRg3miHNrw2bGxrd63tfMEmJob')
print(addr.balance)


# To pull up and explore a transaction; This uses an example transaction
tx = blockexplorer.get_tx('d4af240386cdacab4ca666d178afc88280b620ae308ae8d2585e9ab8fc664a94')


# Blockchain posts must be hexlified first. Here is a function to change a string to hex...
data = binascii.hexlify('here is where you would put the transaction data to be hexlified.')


# Now, to push (or "broadcast") the above data to the blockchain, do the following...
pushtx.pushtx(data)


# Here is another example which uses a valid hex string as an example...

hex_encoded_string = '0100000001fd468e431cf5797b108e4d22724e1e055b3ecec59af4ef17b063afd36d3c5cf6010000008c4930460221009918eee8be186035be8ca573b7a4ef7bc672c59430785e5390cc375329a2099702210085b86387e3e15d68c847a1bdf786ed0fdbc87ab3b7c224f3c5490ac19ff4e756014104fe2cfcf0733e559cbf28d7b1489a673c0d7d6de8470d7ff3b272e7221afb051b777b5f879dd6a8908f459f950650319f0e83a5cf1d7c1dfadf6458f09a84ba80ffffffff01185d2033000000001976a9144be9a6a5f6fb75765145d9c54f1a4929e407d2ec88ac00000000'

pushtx.pushtx(hex_encoded_string)