Ejemplo n.º 1
0
def skHex():
    hex = input("Introduce the hexadecimal secret key: ")
    bin = bin(int(hex, 16))[2:]
    b58 = bitcoin.hex_to_b58check(hex, magicbyte=128)
    # pub_wif = base58(b58)
    print(BRed + "PRIVATE INFORMATION (DO NOT SHARE WITH ANYONE):")
    print(BRed + "The binary secret key is:" + Red, bin)
    print(BRed + "The hexadecimal secret key is:" + Red, hex)
    print(BRed + "The B58Check WIF compressed secret key is:" + Red, b58)
    # print(BRed + "WIF (public key) is:" + Red, pub_wif)
    quit()
def makeTestMemberKeys():
    member_names = ["member_%s" % x for x in "abcdefghijklmnopqrstuvwxyz"]

    privkeys = [
        bitcoin.hex_to_b58check(bitcoin.sha256(member), 0x80)
        for member in member_names
    ]

    addresses = [bitcoin.privkey_to_address(priv) for priv in privkeys]

    return member_names, addresses, privkeys
Ejemplo n.º 3
0
def hex_to_address(value):
    if len(value) == 42:
        version = 0
        value = value[2:]
    elif len(value) == 44:
        version = int(value[:4], 16)
        value = value[4:]
    else:
        raise ValueError("Invalid length")

    return hex_to_b58check(value, magicbyte=version)
Ejemplo n.º 4
0
def hex_to_address(value):
    if len(value) == 42:
        version = 0
        value = value[2:]
    elif len(value) == 44:
        version = int(value[:4], 16)
        value = value[4:]
    else:
        raise ValueError("Invalid length")

    return hex_to_b58check(value, magicbyte=version)
Ejemplo n.º 5
0
def skBinary():
    bin = input("Introduce the binary secret key: ")
    hex = format(int(bin, 2), 'x').upper()
    b58 = bitcoin.hex_to_b58check(hex, magicbyte=128)
    pub_key = wif_to_key(b58)
    print(BRed + "PRIVATE INFORMATION (DO NOT SHARE WITH ANYONE):")
    print(BRed + "The binary secret key is:" + Red, bin)
    print(BRed + "The hexadecimal secret key is:" + Red, hex)
    print(BRed + "The B58Check WIF compressed secret key is:" + Red, b58)
    print(BGreen + "PUBLIC INFORMATION (SAFE TO SHARE)")
    print(BGreen + "WIF (public key) is:" + Green, pub_key)
    quit()
Ejemplo n.º 6
0
def checkTransaction(transactiontext):
    try:
        transactiontext.strip()
        deserialized = bitcoin.deserialize(transactiontext)
        for item in deserialized['outs']:
            out = item['script']
            subString = out[6:len(out) - 4]
            add = bitcoin.hex_to_b58check(subString, 111)
            if add == bitcoinAddress:
                return True
        return False
    except:
        return False
Ejemplo n.º 7
0
 def get_addresses(cls, data, script_type):
     candidate_nonstandard = False
     try:
         if script_type == "pubkeyhash" and len(data['s'][2]) == 40:
             return [hex_to_b58check(data['s'][2].encode('utf-8'), data['p']['pub'])]
         elif script_type == "scripthash" and len(data['s'][1]) == 40:
             return [hex_to_b58check(data['s'][1].encode('utf-8'), data['p']['p2sh'])]
         elif script_type == "multisig":
             addrs = []
             for i in range(1, int(SCRIPTS[data['s'][-2]])+1):
                 if len(data['s'][i]) not in (130, 66, 78):
                     candidate_nonstandard = True
                 if isValidPubKey(data['s'][i]):
                     k = pubtoaddr(data['s'][i].encode('utf-8'))
                     addrs.append(k)
             if candidate_nonstandard:
                 raise VoutDecoderException('','','')
             return addrs
         elif script_type == "pubkey":
             return [pubtoaddr(data['s'][0].encode('utf-8'), 0x00)] if isValidPubKey(data['s'][0]) else []
     except (AttributeError, TypeError):
         raise VoutDecoderException('','','')
     return []
Ejemplo n.º 8
0
def get_postings():
    """
    Retrive all books for sale in the mempool

    Returns:
        current_postings (list): list of current postings
            each element is tuple of (poster, isbn, price, quality)
    """
    postings = []
    canceled_postings = []
    current_postings = []
    txs = bitcoin.history(settings.MARKET_ADDRESS)
    for tx in txs:
        poster, isbn, price = None, None, None
        fetched = bitcoin.fetchtx(tx['output'].split(':')[0])
        tx_outputs = bitcoin.deserialize(fetched)['outs']
        tx_inputs = bitcoin.deserialize(
            bitcoin.fetchtx(
                bitcoin.deserialize(fetched)['ins'][0]['outpoint']
                ['hash']))['outs']
        for input in tx_inputs:
            if input['script'].startswith('76a914'):
                try:
                    text = input['script'].lstrip('76a914').rstrip('88ac')
                    poster = bitcoin.hex_to_b58check(text)
                except:
                    pass
        for output in tx_outputs:
            if output['script'].startswith('6a'):
                text = str(binascii.unhexlify(output['script'][2:]))
                components = text.split('-')
        if len(components) == 3:
            isbn, price, quality = components
            isbn = isbn[-10:]
        if poster and isbn and price and quality:
            if price == '0':
                canceled_postings.append((poster, isbn))
            else:
                postings.append((poster, isbn, price, quality))
    for posting in postings:
        if (posting[0], posting[1]) not in canceled_postings:
            current_postings.append(posting)
    return list(set(current_postings))
Ejemplo n.º 9
0
def get_messages():
    """
    Gets inbox messages from the mempool

    Returns:
        messages (dict): dict of messages
            {sender: {message_num: {submessage_num: message}}}
    """
    messages = defaultdict(dict)
    priv, pub, addr = books.read_wallet()
    txs = bitcoin.history(addr)
    for tx in txs:
        sender, message_num, submessage_num, message = None, None, None, None
        fetched = bitcoin.fetchtx(tx['output'].split(':')[0])
        tx_outputs = bitcoin.deserialize(fetched)['outs']
        tx_inputs = bitcoin.deserialize(
            bitcoin.fetchtx(
                bitcoin.deserialize(fetched)['ins'][0]['outpoint']
                ['hash']))['outs']
        for output in tx_outputs:
            if output['script'].startswith('6a'):
                text = str(binascii.unhexlify(output['script'].lstrip('6a')))
                message_num = text[1]
                submessage_num = text[2]
                message = text[3:]
        for input in tx_inputs:
            try:
                if input['script'].startswith('76a914'):
                    text = input['script'].lstrip('76a914').rstrip('88ac')
                    sender = bitcoin.hex_to_b58check(text)
            except:
                pass
        if sender and message:
            if sender != addr:
                if sender not in messages:
                    messages[sender] = defaultdict(dict)
                messages[sender][message_num].update({submessage_num: message})
    return messages
Ejemplo n.º 10
0
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys

from bitcoin import b58check_to_hex, hex_to_b58check

if len(sys.argv) not in [2, 3]:
    print("Usage: convertAddress.py ADDRESS [TO-MAGIC-BYTE]")
    sys.exit(-1)

addr = sys.argv[1]
if len(sys.argv) >= 3:
    magic = int(sys.argv[2])
else:
    magic = 52

keyHex = b58check_to_hex(addr)
newAddr = hex_to_b58check(keyHex, magic)
print(newAddr)
Ejemplo n.º 11
0
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import sys

from bitcoin import b58check_to_hex, hex_to_b58check

parser = argparse.ArgumentParser ()
parser.add_argument ("--address", required=True,
                     help="the address to convert")
parser.add_argument ("--magic-byte", dest="magic", default=52, type=int,
                     help="the target 'magic' version byte")
parser.add_argument ("--update-file", dest="updatefile", default="",
                     help="if set, replace all occurances in the given file")
args = parser.parse_args ()

keyHex = b58check_to_hex (args.address)
newAddr = hex_to_b58check (keyHex, args.magic)
print (newAddr)

if args.updatefile != "":
  with open (args.updatefile, "r") as f:
    lines = f.readlines ()
  with open (args.updatefile, "w") as f:
    for l in lines:
      f.write (str.replace (l, args.address, newAddr))
Ejemplo n.º 12
0
# Check that the wallet is unlocked.
for rpc in [huc, xaya]:
  info = rpc.getwalletinfo ()
  if 'unlocked_until' in info and info['unlocked_until'] < 1000000000:
    sys.exit ("The wallets must be unlocked")

# Go through the snapshot data and look for addresses that are in the HUC
# wallet we own.
totalHuc = Decimal ('0.00000000')
totalChi = Decimal ('0.00000000')
privkeys = []
for entry in snapshot:
  info = huc.getaddressinfo (entry['address']['huc'])
  if info['ismine']:
    log.info ("Found address: %s" % entry['address']['huc'])
    totalHuc += Decimal (entry['amount']['huc']).quantize (PRECISION)
    totalChi += Decimal (entry['amount']['chi']).quantize (PRECISION)
    pkHuc = huc.dumpprivkey (entry['address']['huc'])
    keyHex = b58check_to_hex (pkHuc)
    pkChi = hex_to_b58check (keyHex, CHI_PRIVKEY_VERSION)
    privkeys.append (pkChi)
log.info ("Total HUC amount eligible: %s" % totalHuc)
log.info ("Total CHI amount claimed: %s" % totalChi)

# Import the found addresses.
for pk in privkeys:
  xaya.importprivkey (pk, LABEL, False)
log.info ("Imported %d private keys.  You need to manually rescan now."
            % len (privkeys))
Ejemplo n.º 13
0
def admSeeTransaction():
    print '<div class="alert alert-danger"><h3><b>Fazer upload das transações não carregadas:</b></h3>'
    print '<form action="" method="post">'
    #table with selectble entries
    print '<table class="table">'
    #header
    print '<tr>'
    print '<th></th>'
    print '<th>Horário</th>'
    print '<th>Valor</th>'
    print '<th>ID da transação</th>'
    print '</tr>'
    #content
    with con:
        cur = con.cursor()
        not_uploaded = ('FALSE', )
        cur.execute("SELECT * FROM Transaction_Info WHERE verified =?",
                    not_uploaded)
        rows = cur.fetchall()
        for row in rows:
            value = ""
            transaction_info = row[1]
            transaction_date = row[3]

            #strange thing happens: there is always a char 0x80 here, I need remove it to correctly decode the transaction
            deserialized = transaction_info.decode('utf8').encode(
                'ascii', errors='ignore')
            deserialized = bitcoin.deserialize(deserialized)
            #deserialized = bitcoin.deserialize(row[1])

            txinfo_hex = transaction_info.decode("hex")
            transaction_i = hashlib.sha256(txinfo_hex).digest()
            transaction_id = hashlib.sha256(transaction_i).digest()
            transaction_id = transaction_id[::-1].encode('hex_codec')

            for item in deserialized['outs']:
                out = item['script']
                subString = out[6:len(out) - 4]
                endereco = bitcoin.hex_to_b58check(subString, 111)
                if endereco == bitcoinAddress:
                    value = item['value'] / float(100000000)
                    #value_btc = value/float(100000000)
            print '<tr>'
            print '<td>'
            #checkbox here
            print "<input type=\"checkbox\" name=\"%s\" value=\"on\" checked>" % (
                transaction_info)
            print '</td>'
            print '<td>'
            #time here
            print transaction_date
            print '</td>'
            print '<td>'
            #value
            print value
            print ' BTC'
            print '</td>'
            print '<td>'
            #transaction here
            print transaction_id
            print '</td>'
            print '</tr>'
    print '</table>'
    print '<input type="hidden" name="upload_tx" value="upload_tx">'
    print '<button type="submit" class="btn btn-default">Fazer upload das transações selecionadas</button>'
    print '</form>'
    #botao para submeter todas as transacoes
    print '<form action="" method="post"><input type="hidden" name="uploadAll" value="uploadAll"><button type="submit" class="btn btn-default" value="Submit">Fazer upload de todas as transações</button></form>'
    print '</div>'
    #botao para expandir transacoes carregadas
    print '<button class="btn btn-default" id="seetrans">Mostrar as transações carregadas</button>'
    print '<p></p>'
    #info das transacoes carregadas
    print '<div id="uploaded" style="display: none;" >'
    #search uploaded transactions
    print '<div class="alert alert-danger"><h3><b>Deletar as transações carregadas:</b></h3>'
    print '''<form onsubmit="return confirm('Voce tem certeza que quer deletar as transações?')" action="" method="post">'''
    #table with selectble entries
    print '<table class="table">'
    #header
    print '<tr>'
    print '<th></th>'
    print '<th>Horário</th>'
    print '<th>Valor</th>'
    print '<th>ID da transação</th>'
    print '</tr>'
    #content
    with con:
        cur = con.cursor()
        uploaded = ('TRUE', )
        cur.execute("SELECT * FROM Transaction_Info WHERE verified =?",
                    uploaded)
        rows = cur.fetchall()
        for row in rows:
            value = ""
            transaction_info = row[1]
            transaction_date = row[3]

            #strange thing happens: there is always a char 0x80 here, I need remove it to correctly decode the transaction
            deserialized = transaction_info.decode('utf8').encode(
                'ascii', errors='ignore')
            deserialized = bitcoin.deserialize(deserialized)
            #deserialized = bitcoin.deserialize(row[1])

            txinfo_hex = transaction_info.decode("hex")
            transaction_i = hashlib.sha256(txinfo_hex).digest()
            transaction_id = hashlib.sha256(transaction_i).digest()
            transaction_id = transaction_id[::-1].encode('hex_codec')

            for item in deserialized['outs']:
                out = item['script']
                subString = out[6:len(out) - 4]
                endereco = bitcoin.hex_to_b58check(subString, 111)
                if endereco == bitcoinAddress:
                    value = item['value'] / float(100000000)
                    #value_btc = value/float(100000000)
            print '<tr>'
            print '<td>'
            #checkbox here
            print "<input type=\"checkbox\" name=\"%s\" value=\"on\">" % (
                transaction_info)
            print '</td>'
            print '<td>'
            #time here
            print transaction_date
            print '</td>'
            print '<td>'
            #value
            print value
            print ' BTC'
            print '</td>'
            print '<td>'
            #transaction here
            print transaction_id
            print '</td>'
            print '</tr>'
    print '</table>'
    print '<input type="hidden" name="delete_tx" value="delete_tx">'
    print '<button type="submit" class="btn btn-default">Deletar as transações selecionadas</button>'
    print '</form>'
    print '</div>'
    print '</div>'
Ejemplo n.º 14
0
    print '<form action="" method="post"><input type="hidden" name="hiddenCost" id="hiddenCost" value=""><button type="submit" class="btn btn-lg" value="Submit">Avançar</button></form>'
    print '</div>'
    #responseForm()
    #admLoginPart()
else:
    if checkTransaction(transactionText):
        value = ""
        value_btc = ""
        endereco = ""
        deserialized = transactionText.strip()
        data = ""
        deserialized = bitcoin.deserialize(deserialized)
        for item in deserialized['outs']:
            out = item['script']
            subString = out[6:len(out) - 4]
            endereco = bitcoin.hex_to_b58check(subString, 111)
            if endereco == bitcoinAddress:
                value = item['value']
                value_btc = value / float(100000000)

        with con:
            cur = con.cursor()
            #to prevent duplication of records in data base
            #get current time
            ts = time.time()
            st = datetime.datetime.fromtimestamp(ts).strftime(
                '%d-%m-%Y %H:%M:%S')
            cur.execute(
                "SELECT * FROM Transaction_Info WHERE transaction_text = ?",
                (transactionText, ))
            data = cur.fetchall()
Ejemplo n.º 15
0
from bitcoin import b58check_to_hex, hex_to_b58check

CHI_ADDRESS_VERSION = 28
INPUT_FILE = 'snapshot-balances.json'
PRECISION = Decimal('1.00000000')
CHI_PER_HUC = Decimal('0.23338000')

with open(INPUT_FILE) as f:
    hucBalances = json.load(f)

output = []
totalChi = Decimal('0.00000000')
for hucAddr, val in hucBalances['addresses'].items():
    keyHex = b58check_to_hex(hucAddr)
    chiAddr = hex_to_b58check(keyHex, CHI_ADDRESS_VERSION)

    hucValue = Decimal(val).quantize(PRECISION)
    hucRounded = int(val)
    chiValue = hucRounded * CHI_PER_HUC

    obj = {
        "address": {
            "huc": hucAddr,
            "chi": chiAddr,
        },
        "amount": {
            "huc": float(hucValue),
            "full_huc": hucRounded,
            "chi": float(chiValue),
        },
def makeTestKey(name):
    privkey = bitcoin.hex_to_b58check(bitcoin.sha256(name), 0x80)

    address = bitcoin.privkey_to_address(privkey)

    return privkey, address