Exemplo n.º 1
0
def Patikra():
    p = RawProxy()
    BHeight = 277316
    BHash = p.getblockhash(BHeight)
    Block = p.getblock(BHash)
    BVer = Block['version']
    BPrevHash = Block['previousblockhash']
    BNonce = Block['nonce']
    BTime = Block['time']
    BMerkle = Block['merkleroot']
    BBits = Block['bits']
    BPrevHash = SwapOrder(BPrevHash)
    BMerkle = SwapOrder(BMerkle)
    BBits = SwapOrder(BBits)
    BNonce = Endian(BNonce)
    BTime = Endian(BTime)
    BVer = Endian(BVer)
    Hex = (BVer + BPrevHash + BMerkle + BTime + BBits + BNonce)
    HexBinary = codecs.decode(Hex, 'hex')
    Hash1 = hashlib.sha256(HexBinary).digest()
    Hash2 = hashlib.sha256(Hash1).digest()
    Hash3 = codecs.encode(Hash2[::-1], 'hex_codec')
    FinalHash = codecs.decode(Hash3)
    print("Block Hash", BHash)
    print("Verified Block Hash", FinalHash)
Exemplo n.º 2
0
def search_for_block_by_header(header):
    p = RawProxy()
    try:
        block_info = p.getblock(header)
        block_info['resulttype'] = 'block'
        return block_info
    except:
        return None
Exemplo n.º 3
0
def get_txs(block_height):
    p = RawProxy()
    blockhash = p.getblockhash(block_height)
    block = p.getblock(blockhash)
    transactions = block['tx']

    for txid in transactions:
        print txid
Exemplo n.º 4
0
def checkBlock():
    hexcoding = 'hex_codec'

    p = RawProxy()
    blockId = raw_input("Enter Block Id: ")

    blockhash = p.getblockhash(int(blockId))

    block = p.getblock(blockhash)

    version = block['versionHex']
    hashPrevBlock = block['previousblockhash']
    hashMerkleRoot = block['merkleroot']
    time = block['time']
    bits = block['bits']
    nonce = block['nonce']

    nonce = hex(int(0x100000000) + int(nonce))[-8:]
    time = hex(int(0x100000000) + int(time))[-8:]

    version = (version.decode(hexcoding))[::-1].encode(hexcoding)
    hashPrevBlock = (hashPrevBlock.decode(hexcoding))[::-1].encode(hexcoding)
    hashMerkleRoot = (hashMerkleRoot.decode(hexcoding))[::-1].encode(hexcoding)
    time = (time.decode(hexcoding))[::-1].encode(hexcoding)
    bits = (bits.decode(hexcoding))[::-1].encode(hexcoding)
    nonce = (nonce.decode(hexcoding))[::-1].encode(hexcoding)

    header_hex = (version + hashPrevBlock + hashMerkleRoot + time + bits +
                  nonce)

    header_bin = header_hex.decode('hex')
    hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest()

    print("Calculated hash:")
    print(hash[::-1].encode(hexcoding))
    print("First hash:")
    print(blockhash)
Exemplo n.º 5
0
from bitcoin.rpc import RawProxy
from hashlib import sha256
import binascii
import struct


def hexify(value, type):
    return binascii.hexlify(struct.Struct(type).pack(value))


p = RawProxy()

blockheight = 1337

blockhash = p.getblockhash(blockheight)
block = p.getblock(blockhash)

block_version = block['version']
previous_hash = block['previousblockhash']
hash_merkle_root = block['merkleroot']
bits = block['bits']
timestamp = block['time']
nonce = block['nonce']

header_hex = '{block_version}{previous_hash}{hash_merkle_root}{timestamp}{bits}{nonce}'.format(
    block_version=hexify(block_version, '<L'),
    previous_hash=binascii.hexlify(previous_hash.decode('hex')[::-1]),
    hash_merkle_root=binascii.hexlify(hash_merkle_root.decode('hex')[::-1]),
    timestamp=hexify(timestamp, '<L'),
    bits=binascii.hexlify(bits.decode('hex')[::-1]),
    nonce=hexify(nonce, '<L'))
Exemplo n.º 6
0
print(a)

#check if hash is correct


def swapOrder(data):
    x = ""
    k = len(data) / 2
    for i in range(0, k):
        byte = data[2 * i] + data[2 * i + 1]
        x = byte + x
    return x


block_hash = p.getblockhash(605730)
block = p.getblock(block_hash)
header = (swapOrder(block["versionHex"]) +
          swapOrder(block["previousblockhash"]) +
          swapOrder(block["merkleroot"]) +
          swapOrder('{:08x}'.format(block["time"])) +
          swapOrder(block["bits"]) + swapOrder('{:08x}'.format(block["time"])))

header_bin = header.decode('hex')
check = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest()

print("Checked hash: ")
print check[::-1].encode('hex_codec')
print("Hash: ")
print block['hash']
Exemplo n.º 7
0
class BlockThread(threading.Thread):
    """
        A block, a thread.
    """
    p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
    mod_sqrt_power = (p + 1) // 4

    def __init__(self, args=()):
        super(BlockThread, self).__init__()
        self.queue = args[0]
        self.rpc_addr = args[1]
        self.rpc_port = args[2]
        self.proxy = None
        self.nblock = 0
        self._stop_event = threading.Event()

    def init_rpc_co(self):
        try:
            if (self.rpc_addr):
                self.proxy = RawProxy(service_url=self.rpc_addr, service_port=self.rpc_port)
            else:
                self.proxy = RawProxy(service_port=self.rpc_port)
        except Exception as e:
            perror("Unable to connect: " + str(e))

    def modular_sqrt(self, a):
        """
            Return n where n * n == a (mod p).
            If no such n exists, an arbitrary value will be returned. From pycoin.
        """
        return pow(a, self.mod_sqrt_power, self.p)

    def get_y(self, x, sign):
        """
            Get the Y coordinate from a compressed key.
            -x:     x coordinate
            -sign:  sign of Y
        """
        y_squared = (x**3 + 7) % self.p
        y = self.modular_sqrt(y_squared)
        if (sign == "02" and y & 1) or (sign == "03" and not y & 1) :
            return -y % self.p
        else:
            return y

    def run(self):
        while(1):
            if self.stopped() and self.nblock == 0:
                logging.info('%s Stopped', self.name)
                break
            if self.nblock:
                self.init_rpc_co()
                #logging.info('%s running with %s', self.name, self.nblock)
                keys = []
                bhash = self.proxy.getblockhash(self.nblock)
                block = self.proxy.getblock(bhash)
                for txid in block['tx']:
                    data = self._get_keys(txid, self.nblock)
                    if data == None or len(data) == 0:
                        continue
                    keys += data
                keys = dict((x[2], x) for x in keys).values() # delete duplicates in list
                for elt in keys:
                    if self.queue.full():
                        self.queue.join()
                    self.queue.put(elt)
                self.nblock = 0
                self.proxy.close()
                self.proxy = None
        return

    def _get_keys(self, txid, block):
        """
            Retrieve all keys from a transaction and construct a list according
            to the db schema.
            -txid:  transaction id
            -block: block number
        """
        tx = self.proxy.getrawtransaction(txid)
        tx_d = self.proxy.decoderawtransaction(tx)

        keys = []
        return_keys = []
        for elt in tx_d['vin']:
            if 'coinbase' in elt.keys():
                continue
            if 'txinwitness' in elt.keys():
                tab = elt['txinwitness']
            elif 'scriptSig' in elt.keys():
                sc = elt['scriptSig']
                tab = [x for x in sc['asm'].split(' ')]

            #If there is a redeem script
            rds = [x for x in tab if x[0] == '5']
            if (len(rds) > 0):
                for x in rds:
                    keys += [p for p in self.proxy.decodescript(x)['asm'].split(' ') if
                            p[0:2] in ['02', '03', '04']]
            else:
                keys += [p for p in tab if p[0:2] in ['02', '03', '04']]

            for key in keys:
                sign = key[:2]
                if sign != "04":
                    #Because sometimes very strange keys, and also because
                    #there are "0"
                    if (len(key) < 60 or len(key) > 70): continue
                    sx = '0x' + key[2:].upper()
                    x = int(sx, 16)
                    y = self.get_y(x, sign)
                    sy = "%X" % y
                    #keys.append([tx, nblock, hash, ])
                else:
                    if (len(key) < 120 or len(key) > 136): continue
                    sx = key[2:66].upper()
                    x = int(sx, 16)
                    sy = key[66:].upper()
                    y = int(sy, 16)

                hash = P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(key), 0)

                return_keys.append([block, txid, str(hash), sx, sy])

            return return_keys

    def is_working(self):
        """
            Return True if working.
        """
        if self.nblock:
            return True
        else:
            return False

    def set_block(self, nblock):
        """
            Set self.nblock.
            -nblock:    block number
        """
        self.nblock = nblock

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()
Exemplo n.º 8
0
from bitcoin.rpc import RawProxy
from hashlib import sha256

p = RawProxy()
blockNum = input("write a block's number:\n")
block = p.getblock(p.getblockhash(blockNum))
header = format(block['nonce'], 'x') + str(block['bits']) + format(block['time'], 'x') + str(block['merkleroot']) + str(block['previousblockhash']) + str(block['versionHex'])

# convert to little indian
indian_header = ""
header = header[::-1]
for i in range(0, len(header), 2):
    indian_header += header[i+1]
    indian_header += header[i]

# hashing, "borrowed" from https://en.bitcoin.it/wiki/Block_hashing_algorithm
header_binary = indian_header.decode('hex')
hash = sha256(sha256(header_binary).digest()).digest()
hash = hash[::-1].encode('hex_codec')

print("\nGotten hash:\n" + hash)
print("Block's hash:\n" + block['hash'])
print("Are they the same?")
print(hash == block['hash'])
Exemplo n.º 9
0
#!/usr/bin/env python3

import codecs
from bitcoin.rpc import RawProxy

if __name__ == '__main__':
    conf = input('Please enter path to the configuration file: ')

    proxy = RawProxy(btc_conf_file=conf)
    numblocks = proxy.getblockcount() + 1

    fp = codecs.open('out.csv', 'w', 'utf-8')

    for idx in range(numblocks):
        blockinfo = proxy.getblock(proxy.getblockhash(idx))
        fp.write(','.join(
            map(str, [
                blockinfo['height'],
                blockinfo['time'],
                blockinfo['difficulty'],
            ])) + '\n')

    fp.close()

# End of File
Exemplo n.º 10
0
fw = open('public/transtats.txt', 'w')
writer = csv.writer(fw)

jsonfile = 'public/data.json'
data = []

if os.path.exists(jsonfile):
    with open(jsonfile) as json_data:
        if os.stat(jsonfile).st_size > 0:
            data = json.load(json_data)
else:
    open(jsonfile, 'w')

firstSegwitBlock = 481824

currentHeight = p.getblock(p.getbestblockhash())['height']

startingHeight = currentHeight - 12


def process_block(height, blockhash):

    print('processing block: height=%d hash=%s' % (height, blockhash))
    thisBlockJson = filter(lambda block: block['Height'] == height, data)

    if len(thisBlockJson):

        if thisBlockJson[0]["Height"] == height and thisBlockJson[0][
                "Hash"] == blockhash:
            print('* already processed in db')
            return
Exemplo n.º 11
0
import matplotlib.pyplot as plt

# Bitcoin Core에 접속한다.
p = RawProxy()

def getUtxo(x, n):
    tt = p.getrawtransaction(x, True)
    return tt['vout'][n]['value']

# 블록체인 tip (끝 부분)의 hash, height를 읽어온다
tip = p.getchaintips()

# 마지막 블록을 읽어온다
height = tip[0]['height']
bHash = tip[0]['hash']
block = p.getblock(bHash)

# 마지막 블록의 Tx를 읽는다.
nTx = len(block['tx'])
    
# Tx를 차례대로 읽어가면서 Fee를 계산한다. (Coinbase Tx는 제외)
txFee = []
byteFee = []
accByteFee = []
cnt = 0
for i in range(1, nTx):
    txid = block['tx'][i]
    tx = p.getrawtransaction(txid, True)
    
    # total Input value를 계산한다
    nIn = len(tx['vin'])
import datetime, calendar
import sys
import hashlib
import binascii

p = RawProxy()

if len(sys.argv) != 2:
    print("Too many arguments or no block height passed!")
    sys.exit()

height = int(sys.argv[1])

blockHash = p.getblockhash(height)

block = p.getblock(blockHash)

version = block['version']
hashPrevBlock = block['previousblockhash'].decode('hex')
merkle = block['merkleroot'].decode('hex')
timestamp = block['time']
bits = block['bits']
nonce = block['nonce']

version = pack('<I', version).encode('hex_codec')
hashPrevBlock = hashPrevBlock[::-1].encode('hex_codec')
merkle = merkle[::-1].encode('hex_codec')
timestamp = pack('<I', timestamp).encode('hex_codec')
bits = pack('<I', int(bits, 16)).encode('hex_codec')
nonce = pack('<I', nonce).encode('hex_codec')
Exemplo n.º 13
0
# Function for converting from big-endian to littl-endian (switch most significant with least significant byte at the front)
def endianConversion(input1):
    ba = bytearray.fromhex(input1)
    ba.reverse()
    result = ''.join(format(x, '02x') for x in ba)
    return result


p = RawProxy()

# Write down basic block informaction
blockHeight = int(sys.argv[1])

blockHash = p.getblockhash(blockHeight)

blockHeader = p.getblock(blockHash)

# Gets the full header information in hex format
fullHeader = (endianConversion(blockHeader['versionHex']) +
              endianConversion(blockHeader['previousblockhash']) +
              endianConversion(blockHeader['merkleroot']) +
              endianConversion('{:02x}'.format(blockHeader['time'])) +
              endianConversion(blockHeader['bits']) +
              endianConversion('{:02x}'.format(blockHeader['nonce'])))

binHeader = fullHeader.decode('hex')

# Calculates the hash based on the header information
calculatedHash = hashlib.sha256(hashlib.sha256(binHeader).digest()).digest()

if calculatedHash[::-1].encode('hex_codec') == blockHeader['hash']: