Beispiel #1
0
def load_blocks(num_blocks, block_hash):
    block = blockexplorer.get_block(block_hash)
    for i in range(num_blocks):
        print("parsing block: %s" % block.hash)
        wait_and_load(block, 60, 0)
        print("done with block: %s" % block.hash)
        block = blockexplorer.get_block(block.previous_block)
def load_blocks(num_blocks, block_hash, log_file):
    global CURR_ADDR_ID
    print("starting curr addr id is: " + str(CURR_ADDR_ID))
    block = blockexplorer.get_block(block_hash)
    for i in range(num_blocks):
        print("parsing block: %s" % block.hash)
        wait_and_load(block, 60, 0, log_file)
        print("done with block: %s" % block.hash)
        block = blockexplorer.get_block(block.previous_block)
Beispiel #3
0
def funtion(i):
    a = 1
    print(i)
    while a:
        try:
            block = blockexplorer.get_block(str(i - 1))
            pre_block = str(block.hash)
            block = blockexplorer.get_block(str(i))
            return block, i, pre_block
        except:
            print("Stuck >>>>>>>  waiting")
            time.sleep(2)
Beispiel #4
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'))
Beispiel #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 get_latest_block():
    """
    Return the latest block in the blockchain.
    """
    latest_block_index = blockexplorer.get_latest_block(
        api_code=API_CODE).block_index
    return blockexplorer.get_block(str(latest_block_index), api_code=API_CODE)
Beispiel #7
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))
def get_previous_block(block):
    """
    Return the parent of the given block.
    """
    if block.height == 0:
        return None
    else:
        return blockexplorer.get_block(block.previous_block, api_code = API_CODE)
def get_previous_block(block):
    """
    Return the parent of the given block.
    """
    if block.height == 0:
        return None
    else:
        return blockexplorer.get_block(block.previous_block, api_code=API_CODE)
Beispiel #10
0
def block(block):
    try:
        block = be.get_block(block, api_code=app.api_code)
        transactions = block.transactions
    except APIException as e:
        print('Error ' + str(e))

    return render_template('block.html',
                           block=block,
                           transactions=transactions,
                           current_time=datetime.now().strftime('LLL'))
Beispiel #11
0
    def submitquery(self):
        action=self.details.get()
        if len(self.hash_no.get())==0:
            b=blockexplorer.get_block(self.display_hashvalue['text'])
        else:
            b=blockexplorer.get_block(self.hash_no.get())

        if action == 'hash':
            self.display_value['text'] = b.hash
        elif action == 'version':
            self.display_value['text'] = b.version
        elif action == 'previous_block':
            self.display_value['text'] = b.previous_block
        elif action == 'merkle_root':
            self.display_value['text'] = b.merkle_root
        elif action == 'time':
            self.display_value['text'] = b.time
        elif action == 'bits':
            self.display_value['text'] = b.bits
        elif action == 'fee':
            self.display_value['text'] = b.fee
        elif action == 'nonce':
            self.display_value['text'] = b.nonce
        elif action == 'n_tx':
            self.display_value['text'] = b.n_tx
        elif action == 'size':
            self.display_value['text'] = b.size
        elif action == 'block_index':
            self.display_value['text'] = b.block_index
        elif action == 'main_chain':
            self.display_value['text'] = b.main_chain
        elif action == 'height':
            self.display_value['text'] = b.height
        elif action == 'received_time':
            self.display_value['text'] = b.received_time
        elif action == 'relayed_by':
            self.display_value['text'] = b.relayed_by
        elif action == 'transactions':
            self.display_value['text'] = 'Since this type contains many txns and its attributes displaying only count of txns :'+str(len(b.transactions))
Beispiel #12
0
def test_craziness():
    block_hash = '000000000000000000114f812c5ee0aa6aa6c6c63f50a5bc9158e95223350808'
    address = '1GnbyZEnmc32MtZdd2n5FjwhvxsZ1Vk4z7'

    block = blockexplorer.get_block(block_hash)

    num = 1
    for tx in block.transactions[1:]:
        output_addr = [x.address for x in tx.outputs if x.address is not None]
        if address in output_addr:
            print(num)
            break
        num += 1
Beispiel #13
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')
def funtion(file, n):
    with open(file, 'a') as g:
        writer = csv.writer(g)
        pre_block = ""
        #new_row = 0, 0, 0 ,0 ,0
        #writer.writerow(new_row)
        for i in range(n, n + 5000):
            print(i)
            try:
                block = blockexplorer.get_block(str(i))
                new_row = i, block.hash, str(
                    block.transactions), pre_block, block.nonce
                writer.writerow(new_row)
                pre_block = str(block.hash)
            except:
                print("Stuck >>>>>>>  waiting")
                time.sleep(60)
                i = i - 1
Beispiel #15
0
def main():

	testrun = 0

	while(testrun < 10):
		logger.info("... Starting new testrun ...")
		logger.info("... Looking for new hash ...")
		wait_for_new_block()
		logger.info("New hash found: {0}".format(LATEST_BLOCK_HASH))
		try:
			latest_block = blockexplorer.get_block(LATEST_BLOCK_HASH)
			traverse_block(latest_block)
			update_database()
			clean_up()
			logger.info("Run completed.")
		except ssl.SSLError, e:
			logger.debug("SSLError! {0}".format(e))
			logger.info("Run failed.")
		finally:
    def getBlockDict(blockIndex):
        block = blockexplorer.get_block(blockIndex)
        Hash = block.hash
        version = block.version
        previous_block = block.previous_block
        merkle_root = block.merkle_root
        time = block.time
        bits = block.bits
        fee = block.fee
        nonce = block.nonce
        n_tx = block.n_tx
        size = block.size
        block_index = block.block_index
        main_chain = block.main_chain
        height = block.height
        received_time = block.received_time
        relayed_by = block.relayed_by
        transactions = block.transactions[0]

        blockDict = {
            "hash": Hash,
            "version": version,
            "previous_block": previous_block,
            "merkle_root": merkle_root,
            "time": time,
            "bits": bits,
            "fee": fee,
            "nonce": nonce,
            "n_tx": n_tx,
            "size": size,
            "block_index": block_index,
            "main_chain": main_chain,
            "height": height,
            "received_time": received_time,
            "relayed_by": relayed_by,
            "transactions": transactions
        }

        return blockDict
Beispiel #17
0
import blockchain.blockexplorer as blx
from igraph import Graph
import pickle
import time

#Get all blocks for a particuar date. Adjust starthash and numblocks by getting
#the last block hash and number of blocks mined from blockchain.info
numblocks = 1500
startHash = '0000000000000000006e566f8f2bccd239a1967ea23c37629341539357d0eb2f'


h = startHash
for i in range(numblocks):
    file = open('/media/ritwiksadhu/2C8E33918E335316/Compre group project/bChain4/block' + str(i) + ".dat", mode = 'wb')
    bl = blx.get_block(h)
    pickle.dump(bl, file)
    file.close()
    h = bl.previous_block

#Extract transactions from the blocks, except the chain base transactions.
#Create a graph of addresses transacting with each other, with the weight being
#the volume of transactions.

tx_graph = Graph(directed = True)

#Create and save blockwise graphs
numblocks = 1500
count = 0
skiplist = []
for i in range(numblocks):
Beispiel #18
0
# import blockchain library
from blockchain import blockexplorer
# get a particular block
block = blockexplorer.get_block(
    '0000000000000000000a83ed02c1a99ef00bed35b9be8362267c442fd7328621')
print("Block Fee: %s\n" % block.fee)
print("Block Size: %s\n" % block.size)
print("Block Transactions: %s\n" % block.transactions)
# get the latest block
block = blockexplorer.get_latest_block()
lbhash = block.hash
block = blockexplorer.get_block(lbhash)
print("Latest Block Fee: %s\n" % block.fee)
print("Latest Block Size: %s\n" % block.size)
print("Latest Block Transactions: %s\n" % block.transactions)
Beispiel #19
0
def load_single_block(block_hash):
    write_to_file("parsing block %s" % block_hash)
    block = blockexplorer.get_block(block_hash)
    wait_and_load(block, 30, 2)
def load_single_block(block_hash):
    print("loading single block...")
    block2 = blockexplorer.get_block(block_hash)
    block = blockexplorer.get_block_height(559684)[0]
    print("block hash: " + str(block2.hash))
    print("block hash from height: " + str(block.hash))
def get_payment_flow(address, tx_hash, max_steps=0, follow_address=''):
    # max_steps: int specifying steps from the payment, if 0 we try to use all the already available steps
    # return a list with a tree-like structure, each element is a dict representing a step
    # if max_steps is not null, we get all the steps till max_steps, resuming from file or starting from scratch
    if max_steps:
        try:
            # check if the flow is already available
            return continue_payment_flow(address, tx_hash, max_steps=max_steps)
        except:
            # if it is not already available, start from scratch
            steps_list = []  # index i for step i, each element is a step_dict
            success = False
            while not success:
                block_hash = get_block_hash(get_tx(tx_hash)['height'])
                block = bx.get_block(block_hash)
                tx_index = [
                    tx.tx_index for tx in block.transactions
                    if tx.hash == tx_hash
                ][0]  # payment
                if follow_address:
                    url = 'https://blockchain.info/tree/' + str(
                        tx_index) + '?format=json'
                    d = url2dict(url)
                    follow_found = False
                    for child in d['children']:
                        if 'name' in child.keys() and child[
                                'name'] == follow_address and 'redeemed_tx' in child.keys(
                                ):
                            tx_index = child['redeemed_tx'][0]
                            follow_found = True
                    if not follow_found:
                        return steps_list
                success = True
            tree_url = 'https://blockchain.info/tree/' + str(
                tx_index) + '?format=json'
            tree = url2dict(tree_url)
            step_dict = dict(
            )  # addresses as keys, list of [BTC, redeemed_tx] as value

            node_name = address[:7] + '_0'
            # for each spent output get indices of next level
            step_dict, exchange_found = tree2step_dict(
                step_dict, tree, 0,
                address)  # step from payment to output addresses
            steps_list.append(step_dict)

            success = False
            while not success:
                try:
                    steps_list = do_steps(steps_list,
                                          1,
                                          max_steps,
                                          exchange_found=exchange_found)
                    success = True
                except Exception as e:
                    print(e, 'get_payment_flow')
            save_payment_flow(steps_list, address, tx_hash)
            return steps_list
    # we just get the steps we have
    # if we fail, is because the file does not exist and we must specify max_steps
    else:
        file_path = base_path + '_' + str(address) + '.json'
        with open(file_path, 'r') as fp:
            steps_list = json.load(fp)
        return steps_list
Beispiel #22
0
 def get_block(self, hash=None):
     if hash is None:
         return None
     return blockexplorer.get_block(hash)
Beispiel #23
0
from blockchain import blockexplorer

block = blockexplorer.get_block("")  #add hash
from blockchain import blockexplorer, util
import json

lastBlock = blockexplorer.get_latest_block()

index = lastBlock.height
print index
block1 = blockexplorer.get_block(str(index - 1))



tx1 = block1.transactions

skip1 = True

for x in tx1:
	if skip1:
		skip1 = False
	else:
		outputs = x.outputs
		for z in outputs:
			print z.spent
Beispiel #25
0
#!/usr/bin/env python

# import blockchain library
from blockchain import blockexplorer

# get a particular block
block = blockexplorer.get_block('000000000000000016f9a2c3e0f4c1245ff24856a79c34806969f5084f410680')

print("Block Fee: %s\n" % block.fee)
print("Block size: %s\n" % block.size)
print("Block transactions: %s\n" % block.transactions)

# get the latest block
block = blockexplorer.get_latest_block()
Beispiel #26
0
def load_single_block(block_hash):
    block = blockexplorer.get_block(block_hash)
    db_put(block)
Beispiel #27
0
from blockchain import blockexplorer, util
import json

lastBlock = blockexplorer.get_latest_block()

index = lastBlock.height

block1 = blockexplorer.get_block(str(index))



tx1 = block1.transactions


ipaddressesInput = []
ipaddressesOutput = []
communicationBetweenTwoNodes = {}

f = open("test.txt", 'w')

for i in range(index, 329620, -1):
	block2 = blockexplorer.get_block(str(i))
	tx2 = block2.transactions
	skip1 = True
	skip2 = True
	print i
	for x in tx1:
		if skip1:
			skip1 = False
		else:
			inputs = x.inputs
Beispiel #28
0
ticker = exchangerates.get_ticker()

#mostra o valor do bitcoin a cerca de 15 min
for k in ticker:
    print(k, ticker[k].p15min)

# Converte o valor de uma moeda para o respectivo valor em bitcoin
btc = exchangerates.to_btc('EUR', 100)
print(f"\n100 euros in Bitcoin: {btc}")

#utilizando a lib statistics
stats = statistics.get()
# total de bitcoin minerados
print("Bitcoin mined: %s\n" % stats.btc_mined)

# valor do bitcoin em USD
print(f"Bitcoin market price USD: {stats.market_price_usd}\n")

#utilizando a lib blockexplorer
# retorna um bloco em particular
block = blockexplorer.get_block(
    '0000000000000000002e90b284607359f3415647626447643b9b880ee00e41fa')

#pode-se obter informações desse bloco em particular
print("Block Fee: %s\n" % block.fee)
print("Block size: %s\n" % block.size)
print("Block transactions: %s\n" % block.transactions)

#ultimo bloco
latest_block = blockexplorer.get_latest_block()
Beispiel #29
0
def insert_input(input):
  stmt = "INSERT INTO TRAN_INPUT(trans, value, address) VALUES(?,?,?)"
  cur.execute(stmt, trans)
  return cur.lastrowid

def insert_output(output):
  stmt = "INSERT INTO TRAN_OUTPUT(trans, value, address) VALUES(?,?,?)"
  cur.execute(stmt, output)
  return cur.lastrowid

for date in dates:
  t = int(time.mktime(time.strptime(date, pattern)) * 1000)
  blocks = be.get_blocks(time=t)
  for b in blocks:
    block = be.get_block(b.hash)
    block_insert = [date, block.height, int(block.main_chain), block.time, block.hash, block.received_time]
    block_id = insert_block(block_insert)
    for trans in block.transactions:
      trans_insert = [block_id, trans.time, trans.hash]
      trans_id = insert_trans(trans_insert)
      for i in trans.inputs:
        print i.__dict__
        i_insert = [trans_id, i.value, i.address]
        insert_input(i_insert)
      for o in trans.outputs:
        o_insert = [trans_id, o.value, o.address]
        insert_output(o_insert)


Beispiel #30
0
from blockchain import blockexplorer

blocklist = []

latest_block = blockexplorer.get_latest_block()

block = blockexplorer.get_block(str(latest_block.block_index))
prev_block = block.previous_block

for i in [1,4]:
    blocklist.append(block)
    block = blockexplorer.get_block(prev_block)
    prev_block = block.previous_block

print(blocklist)
Beispiel #31
0
from blockchain import blockexplorer

block = blockexplorer.get_block("0000000000000000001142eb9a7ec815500505555699aa93610a47d88ef1247d")

print(block.fee)
print(block.size)
print(block.transactions)


Beispiel #32
0
from blockchain import blockexplorer, util
import json

block = blockexplorer.get_block(str(329000))

#print block.hash
#data = blockexplorer.get_inventory_data(txs[1].hash)

txs = block.transactions
#print txs[1].hash
#data = blockexplorer.get_inventory_data(txs[1].hash)
#print data.initial_ip

skip = True
for x in txs:
	if (skip):
		skip = False
	else:
		data = blockexplorer.get_inventory_data(x.hash)
		print data.initial_ip
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  8 14:33:25 2021

@author: SushiMahi
"""

from blockchain import blockexplorer

block = blockexplorer.get_block(
    '000000000000000000043639a106ebd31d6b2c4d59d3ce50913e1d85f70ec956')

print("block fee :", block.fee)

print("block size :", block.size)

print("block Transactions :", block.transactions)
Beispiel #34
0
import pprint
import json


def convertToDict(obj):
    attrs = vars(obj)
    sample = {}
    for item in attrs.items():
        key, value = item
        sample[key] = value
    return sample


pp = pprint.PrettyPrinter(indent=2)

blockObj = blockexplorer.get_block(
    '0000000000000000008dd08f62674a12f5e4291030cde5c322735527cb482aa9')

block = convertToDict(blockObj)

block['transactions'] = []

for transaction in blockObj.transactions:
    trans = convertToDict(transaction)
    trans['inputs'] = []
    trans['outputs'] = []
    for input in transaction.inputs:
        trans['inputs'].append(convertToDict(input))
    for output in transaction.outputs:
        trans['outputs'].append(convertToDict(output))
    block['transactions'].append(trans)
Beispiel #35
0
# import blockchain library
from blockchain import blockexplorer

# get a particular block
block = blockexplorer.get_block(
    "00000000000000000010639dfd78a2e9eea1bb4c6ef0f079c1e715101165d07b")

print(block.fee)
print(block.size)
print(block.transactions)
Beispiel #36
0
filelist = []
for filename in path_list:
    if os.path.splitext(filename)[1] == ".dat":
        filelist.append(filename)
# print(filelist)

# for i in filelist:
#     print(i)
#     blk = get_blocks(i)

blk = get_blocks('./../blk00000.dat')
for raw_block in blk:
    b = Block(raw_block)
    bheader = BlockHeader(raw_block)
    # print(block.hash)
    b2 = get_block(b.hash)

    a = {
        "hash": b.hash,
        "basic": {
            "prev_block": bheader.previous_block_hash,
            "mrkl_root": bheader.merkle_root,
            "height": b2.height,
            "time": str(bheader.timestamp),
            "n_tx": b.n_transactions,
            "main_chain": True,
            "fee": b2.fee,
            "nonce": bheader.nonce,
            "bits": bheader.bits,
            "size": b.size,
            "received_time": b2.received_time,
def get_latest_block():
    """
    Return the latest block in the blockchain.
    """
    latest_block_index = blockexplorer.get_latest_block(api_code = API_CODE).block_index
    return blockexplorer.get_block(str(latest_block_index), api_code = API_CODE)