Beispiel #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)
Beispiel #2
0
def get_utxo(index, txid):
    p = RawProxy()
    raw_tx = p.getrawtransaction(txid)
    decoded_tx = p.decoderawtransaction(raw_tx)
    outputs = decoded_tx['vout']
    utxo = outputs[index]
    return utxo['value']
Beispiel #3
0
    def _handle_request(self, r):
        conf_file = os.path.join(self.bitcoind.bitcoin_dir, 'bitcoin.conf')
        brpc = BitcoinProxy(btc_conf_file=conf_file)
        method = r['method']

        # If we have set a mock for this method reply with that instead of
        # forwarding the request.
        if method in self.mocks and type(method) == dict:
            self.mock_counts[method] += 1
            return self.mocks[method]
        elif method in self.mocks and callable(self.mocks[method]):
            self.mock_counts[method] += 1
            return self.mocks[method](r)

        try:
            reply = {
                "result": brpc._call(r['method'], *r['params']),
                "error": None,
                "id": r['id']
            }
        except JSONRPCError as e:
            reply = {
                "error": e.error,
                "code": -32603,
                "id": r['id']
            }
        self.request_count += 1
        return reply
Beispiel #4
0
    def _handle_request(self, r):
        brpc = BitcoinProxy(btc_conf_file=self.bitcoind.conf_file)
        method = r['method']

        # If we have set a mock for this method reply with that instead of
        # forwarding the request.
        if method in self.mocks and type(self.mocks[method]) == dict:
            ret = {}
            ret['id'] = r['id']
            ret['error'] = None
            ret['result'] = self.mocks[method]
            self.mock_counts[method] += 1
            return ret
        elif method in self.mocks and callable(self.mocks[method]):
            self.mock_counts[method] += 1
            return self.mocks[method](r)

        try:
            reply = {
                "result": brpc._call(r['method'], *r['params']),
                "error": None,
                "id": r['id']
            }
        except JSONRPCError as e:
            reply = {
                "error": e.error,
                "code": -32603,
                "id": r['id']
            }
        self.request_count += 1
        return reply
Beispiel #5
0
    def _handle_request(self, r):
        conf_file = os.path.join(self.bitcoind.bitcoin_dir, 'groestlcoin.conf')
        brpc = BitcoinProxy(btc_conf_file=conf_file)
        method = r['method']

        # If we have set a mock for this method reply with that instead of
        # forwarding the request.
        if method in self.mocks and type(method) == dict:
            self.mock_counts[method] += 1
            return self.mocks[method]
        elif method in self.mocks and callable(self.mocks[method]):
            self.mock_counts[method] += 1
            return self.mocks[method](r)

        try:
            reply = {
                "result": brpc._call(r['method'], *r['params']),
                "error": None,
                "id": r['id']
            }
        except JSONRPCError as e:
            reply = {
                "error": e.error,
                "id": r['id']
            }
        self.request_count += 1
        return reply
Beispiel #6
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
Beispiel #7
0
def search_for_block_by_height(height):
    p = RawProxy()
    try:
        int_height = int(height)
        block_hash = p.getblockhash(int_height)
        return search_for_block_by_header(block_hash)
    except:
        return None
Beispiel #8
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
Beispiel #9
0
 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))
Beispiel #10
0
def search_for_transaction_by_txid(txid):
    p = RawProxy()
    try:
        transaction_info = p.getrawtransaction(txid, True)
        transaction_info['resulttype'] = 'transaction'
        return transaction_info
    except:
        return None
Beispiel #11
0
def get_latest_blocks():
    p = RawProxy()
    blocks_to_take = 10
    if request.args.get('count'):
        blocks_to_take = int(blocks_to_take)
    blocks_count = p.getblockcount()
    block_heights = list(range(blocks_count - blocks_to_take, blocks_count))
    block_hashes = list(map(p.getblockhash, block_heights))
    block_hashes.reverse()  # So latest hashes would go first
    return jsonify(block_hashes)
Beispiel #12
0
def get_blockhash():
    p = RawProxy()
    print('Iveskite tikrinamo bloko numeri')
    height = input()
    try:
        blockhash = p.getblockhash(int(height))
        return blockhash
    except Exception as e:
        logging.error(traceback.format_exc())
        globals.control = 0
        return
Beispiel #13
0
    def __getattr__(self, name):
        if name.startswith('__') and name.endswith('__'):
            # Python internal stuff
            raise AttributeError

        # Create a callable to do the actual call
        proxy = BitcoinProxy(btc_conf_file=self.__btc_conf_file__)

        f = lambda *args: proxy._call(name, *args)

        # Make debuggers show <function bitcoin.rpc.name> rather than <function
        # bitcoin.rpc.<lambda>>
        f.__name__ = name
        return f
Beispiel #14
0
class HashValidator:

    __rawProxy = RawProxy()

    def validate(self, blockHeight):

        blockHash = self.__rawProxy.getblockhash(int(blockHeight))
        blockHeader = self.__rawProxy.getblockheader(blockHash)

        headerHex = (self.__toLittleEndian(blockHeader['versionHex']) +
                     self.__toLittleEndian(blockHeader['previousblockhash']) +
                     self.__toLittleEndian(blockHeader['merkleroot']) +
                     self.__toLittleEndian(format(int(blockHeader['time']), 'x')) +
                     self.__toLittleEndian(blockHeader['bits']) +
                     self.__toLittleEndian(format(int(blockHeader['nonce']), 'x')))

        headerBinary = binascii.unhexlify(headerHex)
        newHash = self.__toLittleEndian(hashlib.sha256(hashlib.sha256(headerBinary).digest()).hexdigest())

        if blockHash == newHash:
            return True
        else:
            return False

    def __toLittleEndian(self, input):
        byteArr = bytearray.fromhex(input)
        byteArr.reverse()
        return ''.join(format(x, '02x') for x in byteArr)
Beispiel #15
0
def get_blockchain_info():
    p = RawProxy()
    # Run the getblockchaininfo command, store the resulting data in info
    blockchain_info = p.getblockchaininfo()

    filtered_info = {
        "chainType": blockchain_info["chain"],
        "blockCount": blockchain_info["blocks"],
        "validatedHeadersCount": blockchain_info["headers"],
        "difficulty": str(blockchain_info["difficulty"]),
        "verificationProgress":
        str(blockchain_info["verificationprogress"] * 100),
        "bestBlockHash": str(blockchain_info["bestblockhash"])
    }

    return jsonify(filtered_info)
Beispiel #16
0
    def send_rpc_cmd(self, rpc_cmd, *nodes):

        # print('Sending rpc command: {}'.format(' '.join(rpc_cmd)))
        proxies = {}
        for n in nodes:
            proxies[n] = RawProxy('http://{user}:{password}@{host}:{rpcport}'.format(**self.nodes[n]))

        # try convert rpc params from strings to ints
        for idx, val in enumerate(rpc_cmd):
            try:
                rpc_cmd[idx] = int(val)
            except ValueError:
                if val in {'False', 'false'}:
                    rpc_cmd[idx] = False
                elif val in {'True', 'true'}:
                    rpc_cmd[idx] = True

        for node in nodes:
            retry = 1
            while True:
                try:
                    cmd, *args = rpc_cmd
                    # print("command:", rpc_cmd)
                    output = getattr(proxies[int(node)], cmd)(*args)
                    # print(output)
                    return output
                except JSONRPCError as e:
                    retry += 1
                    if e.error['code'] == -26:
                        raise TxVerifyError('Error during tx validation: {}'.format(e.error['message']))
                    if e.error['code'] != -28 or retry > 3:
                        raise SendCommandError("Error trying to send command to bitcoincli, "
                                               "error code: {}, message: {}".format(e.error['code'],
                                                                                    e.error['message']))
                    sleep(3 * (retry*2))
Beispiel #17
0
class FeeCalculator:

    __rawProxy = RawProxy()

    def calculate(self, trxId):
        trx = self.__getTransaction(trxId)

        inputSum = 0
        outputSum = 0

        for vOutput in trx['vout']:
            outputSum += vOutput['value']

        for vInput in trx['vin']:
            inputSum += self.__getTrxOutputByIndex(vInput['txid'],
                                                   vInput['vout'])

        return inputSum - outputSum

    def __getTrxOutputByIndex(self, trxId, outputIndex):
        trx = self.__getTransaction(trxId)
        itr = 0

        for vOutput in trx['vout']:
            if outputIndex == itr:
                return vOutput['value']
            itr = itr + 1

    def __getTransaction(self, trxId):
        rawTrx = self.__rawProxy.getrawtransaction(trxId)
        return self.__rawProxy.decoderawtransaction(rawTrx)
Beispiel #18
0
    def _handle_request(self, r):
        conf_file = os.path.join(self.bitcoin_dir, "bitcoin.conf")
        brpc = BitcoinProxy(btc_conf_file=conf_file)
        method = r["method"]

        # If we have set a mock for this method reply with that instead of
        # forwarding the request.
        if method in self.mocks and type(method) == dict:
            return self.mocks[method]
        elif method in self.mocks and callable(self.mocks[method]):
            return self.mocks[method](r)

        try:
            reply = {
                "result": brpc._call(r["method"], *r["params"]),
                "error": None,
                "id": r["id"],
            }
        except JSONRPCError as e:
            reply = {"error": e.error, "id": r["id"]}
        return reply
Beispiel #19
0
def Mokestis():
    p = RawProxy()
    #txidd = input("Iveskite transakcija")
    #txid = str(txidd)
    txid = '0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2'
    raw_tx = p.getrawtransaction(txid)
    decoded_tx = p.decoderawtransaction(raw_tx)

    sumIn = 0
    sumOut = 0
    for output in decoded_tx['vin']:
        vinTxId = output['txid']
        raw_vintx = p.getrawtransaction(vinTxId)
        decoded_vintx = p.decoderawtransaction(raw_vintx)
        vin_vout = output['vout']
        for out in decoded_vintx['vout']:
            if (out['n'] == vin_vout):
                sumIn += out['value']

    for output in decoded_tx['vout']:
        sumOut += output['value']

    tx_fee = sumIn - sumOut
    print("Transakcijos: ", txid)
    print("mokestis: ", tx_fee, "BTC")
Beispiel #20
0
def check_block():
    p = RawProxy()
    var = get_blockhash()
    if var is None:
        return
    header = p.getblockheader(var)
    header_hex = (to_little_endian(header['versionHex']) +
                  to_little_endian(header['previousblockhash']) +
                  to_little_endian(header['merkleroot']) +
                  to_little_endian(format(int(header['time']), 'x')) +
                  to_little_endian(header['bits']) +
                  to_little_endian(format(int(header['nonce']), 'x')))

    header_bin = binascii.unhexlify(header_hex)
    block_hask = hashlib.sha256(
        hashlib.sha256(header_bin).digest()).hexdigest()
    block_hask_le = to_little_endian(block_hask)
    if var == block_hask_le:
        print('Bloko hashas yra teisingas')
    else:
        print('Bloko hashas yra neteisingas')
    globals.control = 0
Beispiel #21
0
def find_transaction_fee():
    p = RawProxy()
    print('Iveskite pasirinktos transakcijos id')
    txid = input_txid()
    txinval = 0
    txoutval = 0
    try:
        raw_tx = p.getrawtransaction(txid)
    except Exception as e:
        logging.error(traceback.format_exc())
        globals.control = 0
        return
    decoded_tx = p.decoderawtransaction(raw_tx)
    vins = decoded_tx['vin']
    vouts = decoded_tx['vout']
    for input in vins:
        txinval = txinval + get_utxo(input['vout'], input['txid'])
    for output in vouts:
        txoutval = txoutval + output['value']
    globals.control = 0
    print('Transakcijos kaina:')
    print(f'{txinval - txoutval} BTC')
    return
Beispiel #22
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)
Beispiel #23
0
def Brangiausia():
    p = RawProxy()
    txid = "4410c8d14ff9f87ceeed1d65cb58e7c7b2422b2d7529afc675208ce2ce09ed7d"
    raw_tx = p.getrawtransaction(txid)
    decoded_tx = p.decoderawtransaction(raw_tx)

    sumIn = 0
    sumOut = 0
    for output in decoded_tx['vin']:
        vinTxId = output['txid']
        raw_vintx = p.getrawtransaction(vinTxId)
        decoded_vintx = p.decoderawtransaction(raw_vintx)
        vin_vout = output['vout']
        for out in decoded_vintx['vout']:
            if (out['n'] == vin_vout):
                sumIn += out['value']

    for output in decoded_tx['vout']:
        sumOut += output['value']

    tx_fee = sumIn - sumOut
    print("Transakcijos: ", txid)
    print("mokestis: ", tx_fee, "BTC")
Beispiel #24
0
def checkTrans():
    transValue = 0

    transId = raw_input("Enter transaction Id: ")

    p = RawProxy()

    trans = p.decoderawtransaction(p.getrawtransaction(transId))

    for outputTrans in trans['vin']:

        transIdLocal = outputTrans['txid']
        vout = outputTrans['vout']
        transLocal = p.decoderawtransaction(p.getrawtransaction(transIdLocal))

        for outputTransLocal in transLocal['vout']:

            if outputTransLocal['n'] == vout:
                transValue = transValue + outputTransLocal['value']

    for output in trans['vout']:
        transValue = transValue - output['value']

    print(transValue)
Beispiel #25
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'))
Beispiel #26
0
from bitcoin.rpc import RawProxy

p = RawProxy()

txid = raw_input(
    "Input your transactionID (just type \'no\' if you dont want to) -> ")
if txid == "no":
    txid = "4410c8d14ff9f87ceeed1d65cb58e7c7b2422b2d7529afc675208ce2ce09ed7d"

tx_fee = 0
tx_input = 0
tx_output = 0

#decoce the transaction
raw_tx = p.getrawtransaction(txid)
decoded_tx = p.decoderawtransaction(raw_tx)

# calculate in value
for input in decoded_tx['vin']:
    tx_prev = input['txid']
    tx_prev_index = input['vout']
    # get into prev transaction
    tx_prev_decoded = p.decoderawtransaction(p.getrawtransaction(tx_prev))
    tx_input = tx_input + tx_prev_decoded['vout'][tx_prev_index]['value']

print("Transaction input", tx_input)

#  calculate out value
for output in decoded_tx['vout']:
    tx_output = tx_output + output['value']
Beispiel #27
0
from bitcoin.rpc import RawProxy
p = RawProxy()

def decodeTransaction(transaction_id):
    raw_tx = p.getrawtransaction(transaction_id)
    decoded_tx = p.decoderawtransaction(raw_tx)
    return decoded_tx


sumIn = sumOut = 0
decoded_transaction = decodeTransaction(raw_input("transaction's hash:\n"))

for i in decoded_transaction['vout']:
    sumOut += i['value']

for i in decoded_transaction['vin']:
    # the source transaction
    decoded_input_transaction = decodeTransaction(i['txid'])
    # ['vout'] - a list of outputs
    # [i['vout']] - an output that is connected to the address
    # ['value'] - the final output sum
    sumIn += decoded_input_transaction['vout'][i['vout']]['value']

print("Transaction's fee is " + str(sumIn-sumOut))
# thanks, https://bitcoinj.org/working-with-transactions
from bitcoin.rpc import RawProxy

p = RawProxy()

# Alice's transaction ID
txid = "0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2"

# First, retrieve the raw transaction in hex
raw_tx = p.getrawtransaction(txid)

# Decode the transaction hex into a JSON object
decoded_tx = p.decoderawtransaction(raw_tx)

# Retrieve each of the outputs from the transaction
for output in decoded_tx['vout']:
    print(output['scriptPubKey']['addresses'], output['value'])
# This simple wallet works with bitcoind and will only work with 2-of-3 multisigs
# Using the python-bitcoinlib library

# 如何分布三个私钥的存储
# 一个自己使用,一个存放在wallet provider, 一个放在最安全的地方,一般不用

# 如何来花这个multisig addr中的比特币?
# 比如你想到taobao.com上去花比特币买东西,你这时用自己的私钥来 createrawTransaction,但是这时交易显示的花费是失败的,
# 这时你将signed之后的原始交易发给第三方平台,这时你就让它用私钥来sign你sign过的transaction,这时会显示花费成功
import bitcoin
from bitcoin.rpc import RawProxy

bitcoin.SelectParams('testnet')
p = RawProxy()  #creates an object called p that allows for bitcoind calls

money = p.getbalance()
print(money)
# YOU NEED AT LEAST TWO OF THE PRIVATE KEYS FROM PART ONE linked to your MULTI-SIG ADDRESS
multisigprivkeyone = "cPw3fUfVnhZNNpg8mEnoNcbrk4VhhobDohZBcZdrS3pfP53ymhB2"
multisigprivkeytwo = "cPpjLNPGgvwfCSUuXk1qExmBQB71piHxMUxmukzLr43m38VqsCHo"
multisigprivkeythree = "cT2YurYhGWiShznfwzcsysf1a4koDhP369dtWiKBTyZV1HMTGLEk"
ChangeAddress = "2NBwWtf4mQcmx1mR2tNSsuh21LsoPtbxA79"  # Makes Sure to set your own personal Change Address

SetTxFee = int(0.00005461 * 100000000)

# ask your account, how much money you have
unspent = p.listunspent(
)  # Query wallet.dat file for unspent funds to see if we have multisigs to spend from

print("Your Bitcoin-QT/d has", len(unspent), "unspent outputs")
for i in range(0, len(unspent)):
Beispiel #30
0
from bitcoin.rpc import RawProxy
p = RawProxy()
info = p.getblockchaininfo()
print(info)
Beispiel #31
0
import json
from bitcoin.rpc import RawProxy

p = RawProxy()

blockheight = 234349

blockhash = p.getblockhash(blockheight)

block = p.getblock(blockhash)

transactions = block['tx']

block_value = 0

for txid in transactions:
    tx_value = 0
    raw_tx = p.getrawtransaction(txid)
    decoded_tx = p.decoderawtransaction(raw_tx)

    for output in decoded_tx['vout']:
        tx_value = tx_value + output['value']

    block_value = block_value + tx_value

print("total value in block[{0}]: {1}".format(blockheight, block_value))