Beispiel #1
0
def signTxSegwit(txHex, wif_key):
    tx = Tx.from_hex(txHex)

    my_key = Key.from_text(wif_key)
    script = ScriptPayToAddressWit(b'\0', my_key.hash160()).script()
    redeem = binascii.hexlify(script).decode()

    in_keys = [wif_key]
    hash160_lookup = build_hash160_lookup(
        [Key.from_text(wif).secret_exponent() for wif in in_keys])
    for i in range(0, len(tx.txs_in)):
        p2sh_lookup = build_p2sh_lookup([binascii.unhexlify(redeem)])
        tx.sign_tx_in(hash160_lookup,
                      i,
                      tx.unspents[i].script,
                      hash_type=SIGHASH_ALL,
                      p2sh_lookup=p2sh_lookup)
    return tx.as_hex()
Beispiel #2
0
def test_path_index(mode, pattern, index, 
        set_encoded_secret, dev, cap_menu, pick_menu_item,
        goto_home, cap_story, need_keypress
):
    # Uses any key on Simulator; just checking for operation + entropy level

    goto_home()
    pick_menu_item('Advanced')
    pick_menu_item('Derive Entropy')

    time.sleep(0.1)
    title, story = cap_story()

    assert 'seed value' in story
    assert 'other wallet systems' in story
    
    need_keypress('y')
    time.sleep(0.1)
    
    pick_menu_item(mode) 

    if index is not None:
        time.sleep(0.1)
        for n in str(index):
            need_keypress(n)

    need_keypress('y')

    time.sleep(0.1)
    title, story = cap_story()

    assert f'Path Used (index={index}):' in story
    assert "m/83696968'/" in story
    assert f"/{index}'" in story

    got = re.findall(pattern, story)[0]

    assert len(set(got)) >= 12

    global HISTORY
    assert got not in HISTORY
    HISTORY.add(got)

    if 'words' in mode:
        exp = Mnemonic('english').to_mnemonic(a2b_hex(got)).split()
        assert '\n'.join(f'{n+1:2d}: {w}' for n, w in enumerate(exp)) in story
    elif 'XPRV' in mode:
        node = BIP32Node.from_hwif(got)
        assert str(b2a_hex(node.chain_code()), 'ascii') in story
        assert hex(node.secret_exponent())[2:] in story
    elif 'WIF' in mode:
        key = Key.from_text(got)
        assert hex(key.secret_exponent())[2:] in story
Beispiel #3
0
def parse_as_secret_exponent(s):
    v = parse_as_number(s)
    if v and v < secp256k1._r:
        return v


secret_exponent = parse_as_secret_exponent(secret)
if secret_exponent:
    privkey = Key(secret_exponent=secret_exponent)

if SEC_RE.match(secret):
    privkey = Key.from_sec(unhexlify(secret))
else:
    try:
        privkey = Key.from_text(secret)
    except encoding.EncodingError:
        pass

# Define vars automatically from privkey (could be manually, if you had the values)
privkey_uncompressed = '%x' % privkey.secret_exponent()
pubkey_uncompressed = hexlify(privkey.sec(use_uncompressed=True))

##
# Prepare pubkey for encrypting
##

pubkey_bin_tmp = arithmetic.changebase(pubkey_uncompressed[2:],
                                       16,
                                       256,
                                       minlen=64)
Beispiel #4
0
def test_generate(mode, pdf, dev, cap_menu, pick_menu_item, goto_home, cap_story, need_keypress, microsd_path):
    # test UX and operation of the 'bitcoin core' wallet export
    mx = "Don't make PDF"

    goto_home()
    pick_menu_item('Advanced')
    try:
        pick_menu_item('Paper Wallets')
    except:
        raise pytest.skip('Feature absent')

    time.sleep(0.1)
    title, story = cap_story()

    assert 'pick a random' in story
    assert 'MANY RISKS' in story

    need_keypress('y')

    time.sleep(0.1)
    if mode == 'segwit':
        pick_menu_item('Classic Address')
        pick_menu_item('Segwit/Bech32')
        time.sleep(0.5)

    if pdf:
        assert mx in cap_menu()
        shutil.copy('../docs/paperwallet.pdf', microsd_path('paperwallet.pdf'))
        pick_menu_item(mx)
        need_keypress('y')

        time.sleep(0.1)
        title, story = cap_story()
        assert 'Pick PDF' in story

        pick_menu_item('paperwallet.pdf')


    pick_menu_item('GENERATE WALLET')

    time.sleep(0.1)
    title, story = cap_story()

    assert 'Created file' in story

    story = [i for i in story.split('\n') if i]
    if not pdf:
        fname = story[-1]
    else:
        fname = story[-2]
        pdf_name = story[-1]
        assert pdf_name.endswith('.pdf')

    assert fname.endswith('.txt')

    path = microsd_path(fname)
    with open(path, 'rt') as fp:
        hdr = None
        for ln in fp:
            ln = ln.rstrip()
            if not ln: continue

            if ln[0] != ' ':
                hdr = ln
                continue

            if '█' in ln:
                continue

            val = ln.strip()
            if 'Deposit address' in hdr:
                assert val == fname.split('.', 1)[0].split('-', 1)[0]
                txt_addr = val
                if mode != 'segwit':
                    addr = Key.from_text(val)
                else:
                    hrp, data = bech32_decode(val)
                    decoded = convertbits(data[1:], 5, 8, False)[-20:]
                    assert hrp in {'tb', 'bc' }
                    addr = Key(hash160=bytes(decoded), is_compressed=True, netcode='XTN')
            elif hdr == 'Private key:':         # for QR case
                assert val == wif
            elif 'Private key' in hdr and 'WIF=Wallet' in hdr:
                wif = val
                k1 = Key.from_text(val)
            elif 'Private key' in hdr and 'Hex, 32 bytes' in hdr:
                k2 = Key(secret_exponent=from_bytes_32(a2b_hex(val)), is_compressed=True)
            elif 'Bitcoin Core command':
                assert wif in val
                assert 'importmulti' in val or 'importprivkey' in val
            else:
                print(f'{hdr} => {val}')
                raise ValueError(hdr)

        assert k1.sec() == k2.sec()
        assert k1.public_pair() == k2.public_pair()
        assert addr.address() == k1.address()

        os.unlink(path)

    if not pdf: return

    path = microsd_path(pdf_name)
    with open(path, 'rb') as fp:

        d = fp.read()
        assert wif.encode('ascii') in d
        assert txt_addr.encode('ascii') in d

        os.unlink(path)
Beispiel #5
0
def process(request):
    if request.method == 'POST':
# auto deposit function
        if request.POST.get('VERY_LONG_RANDOM_STRING'):
            account_record = AccountModel.objects.create(return_address=chikun_address)
            account_record.save()
            deposit_address = master_public_key.subkey(account_record.id).address()
            return HttpResponse(deposit_address)

        response = system('ping -c 1 -w 3 %s > /dev/null 2>&1' % hostname)
        if request.POST.get('v_key') == v_key and response == 0:
# check balance stats for all balance 0's
            zero_list = AccountModel.objects.filter(balance=0)
            if zero_list.exists():

                for i in zero_list:
                    address = master_public_key.subkey(i.id).address()

                    try:
                        balance = Decimal(urlopen('https://%s/q/addressbalance/%s?confirmations=%s&api_code=%s' % (hostname, address, confirmations, api_code)).read()) / 100000000  # REMOTE
                    except Exception as e:
                        lf = open('logFile', 'a')
                        print('try one: ', end='')
                        print(e, file=lf)
                        lf.close()
                        return HttpResponse(status=204)

                    if balance >= Decimal('0.001'):
                        i.balance = balance

                    i.checked += 1
                    i.save()

# match valid accounts and make payments
            nonzero_list = AccountModel.objects.filter(balance__gt=0).order_by('?')
            if len(nonzero_list) > 1:
                v = True
                limit = len(nonzero_list) / 2 if not len(nonzero_list) % 2 else (len(nonzero_list) - 1) / 2
                nonzero_list = nonzero_list[:limit * 2]

            else:
                v = False
            if v:
                slice_one = nonzero_list[:limit]
                slice_two = nonzero_list[limit:]

                c = 0
                while c < limit:
                    if not slice_one[c].balance == slice_two[c].balance:
                        (winner, loser) = (slice_one[c], slice_two[c]) if slice_one[c].balance > slice_two[c].balance else (slice_two[c], slice_one[c])

                        winner_key = Key.from_text(request.POST['private_key']).subkey(winner.id)
                        loser_key = Key.from_text(request.POST['private_key']).subkey(loser.id)

                        try:
                            spendables = spendables_for_address('%s&api_code=%s' % (winner_key.address(), api_code)) + spendables_for_address('%s&api_code=%s' % (loser_key.address(), api_code))
                            signed_tx = create_signed_tx(spendables,
                                                         [(chikun_address, int((loser.balance * vig) * 100000000)), winner.return_address],
                                                         wifs=[winner_key.wif(), loser_key.wif()], fee="standard")

                            pushtx(signed_tx.as_hex())

                            ResultModel.objects.create(winning_address=winner_key.address(), winning_deposit=str(winner.balance),
                                                       losing_address=loser_key.address(), losing_deposit=str(loser.balance),
                                                       txid=signed_tx.id()).save()

                            for i in (winner, loser):
                                ArchiveModel.objects.create(**AccountModel.objects.filter(id=i.id).values()[0]).save()
                                AccountModel.objects.filter(id=i.id).delete()

                        except Exception as e:
                            lf = open('logFile', 'a')
                            print('try two: ', end='')
                            print(e, file=lf)
                            lf.close()
                            for i in (winner, loser):
                                BrokenModel.objects.create(**AccountModel.objects.filter(id=i.id).values()[0]).save()
                                AccountModel.objects.filter(id=i.id).delete()

                    c += 1

# remove invalid accounts
            invalid_accounts = AccountModel.objects.filter(checked__gt=24).filter(balance=0)  # four hours
            if invalid_accounts.exists():

                for i in invalid_accounts:
                    InvalidModel.objects.create(**AccountModel.objects.filter(id=i.id).values()[0]).save()
                    AccountModel.objects.filter(id=i.id).delete()

            return HttpResponse(status=204)

    return HttpResponse('<h1>Not Found</h1><p>The requested URL /with was not found on this server.</p>', status=404)
Beispiel #6
0
from pycoin.key.validate import is_public_bip32_valid, is_address_valid
from pycoin.key.Key import Key
from pycoin.tx.tx_utils import create_signed_tx
from pycoin.tx.pay_to import ScriptMultisig, address_for_pay_to_script
from pycoin.encoding import EncodingError

from graphos.sources.model import ModelDataSource
from graphos.renderers import flot

from os import system
from decimal import Decimal
from urllib2 import urlopen

#region Variables

master_public_key = Key.from_text('SECRET_EXTENDED_PUBLIC_KEY')
api_code = 'SECRET_BLOCKCHAIN.INFO_API_CODE'
chikun_address = '12LmXkeVmSL3nBrMMBCPcLw2Jt97G1W4gr'
hostname = 'blockchain.info'
confirmations = 1
vig = Decimal('0.02')
v_key = 'VERY_LONG_RANDOM_STRING'
#endregion

#########
# VIEWS #
#########
def home(request):
    #region GET
    if request.method == "GET":
        form_capcha = CaptchaTestForm()
Beispiel #7
0
def process(request):
    if request.method == 'POST':
        # auto deposit function
        if request.POST.get('VERY_LONG_RANDOM_STRING'):
            account_record = AccountModel.objects.create(
                return_address=chikun_address)
            account_record.save()
            deposit_address = master_public_key.subkey(
                account_record.id).address()
            return HttpResponse(deposit_address)

        response = system('ping -c 1 -w 3 %s > /dev/null 2>&1' % hostname)
        if request.POST.get('v_key') == v_key and response == 0:
            # check balance stats for all balance 0's
            zero_list = AccountModel.objects.filter(balance=0)
            if zero_list.exists():

                for i in zero_list:
                    address = master_public_key.subkey(i.id).address()

                    try:
                        balance = Decimal(
                            urlopen(
                                'https://%s/q/addressbalance/%s?confirmations=%s&api_code=%s'
                                % (hostname, address, confirmations,
                                   api_code)).read()) / 100000000  # REMOTE
                    except Exception as e:
                        lf = open('logFile', 'a')
                        print('try one: ', end='')
                        print(e, file=lf)
                        lf.close()
                        return HttpResponse(status=204)

                    if balance >= Decimal('0.001'):
                        i.balance = balance

                    i.checked += 1
                    i.save()

# match valid accounts and make payments
            nonzero_list = AccountModel.objects.filter(
                balance__gt=0).order_by('?')
            if len(nonzero_list) > 1:
                v = True
                limit = len(nonzero_list) / 2 if not len(
                    nonzero_list) % 2 else (len(nonzero_list) - 1) / 2
                nonzero_list = nonzero_list[:limit * 2]

            else:
                v = False
            if v:
                slice_one = nonzero_list[:limit]
                slice_two = nonzero_list[limit:]

                c = 0
                while c < limit:
                    if not slice_one[c].balance == slice_two[c].balance:
                        (winner, loser) = (
                            slice_one[c], slice_two[c]
                        ) if slice_one[c].balance > slice_two[c].balance else (
                            slice_two[c], slice_one[c])

                        winner_key = Key.from_text(
                            request.POST['private_key']).subkey(winner.id)
                        loser_key = Key.from_text(
                            request.POST['private_key']).subkey(loser.id)

                        try:
                            spendables = spendables_for_address(
                                '%s&api_code=%s' %
                                (winner_key.address(),
                                 api_code)) + spendables_for_address(
                                     '%s&api_code=%s' %
                                     (loser_key.address(), api_code))
                            signed_tx = create_signed_tx(
                                spendables,
                                [(chikun_address,
                                  int((loser.balance * vig) * 100000000)),
                                 winner.return_address],
                                wifs=[winner_key.wif(),
                                      loser_key.wif()],
                                fee="standard")

                            pushtx(signed_tx.as_hex())

                            ResultModel.objects.create(
                                winning_address=winner_key.address(),
                                winning_deposit=str(winner.balance),
                                losing_address=loser_key.address(),
                                losing_deposit=str(loser.balance),
                                txid=signed_tx.id()).save()

                            for i in (winner, loser):
                                ArchiveModel.objects.create(
                                    **AccountModel.objects.filter(
                                        id=i.id).values()[0]).save()
                                AccountModel.objects.filter(id=i.id).delete()

                        except Exception as e:
                            lf = open('logFile', 'a')
                            print('try two: ', end='')
                            print(e, file=lf)
                            lf.close()
                            for i in (winner, loser):
                                BrokenModel.objects.create(
                                    **AccountModel.objects.filter(
                                        id=i.id).values()[0]).save()
                                AccountModel.objects.filter(id=i.id).delete()

                    c += 1

# remove invalid accounts
            invalid_accounts = AccountModel.objects.filter(
                checked__gt=24).filter(balance=0)  # four hours
            if invalid_accounts.exists():

                for i in invalid_accounts:
                    InvalidModel.objects.create(**AccountModel.objects.filter(
                        id=i.id).values()[0]).save()
                    AccountModel.objects.filter(id=i.id).delete()

            return HttpResponse(status=204)

    return HttpResponse(
        '<h1>Not Found</h1><p>The requested URL /with was not found on this server.</p>',
        status=404)
Beispiel #8
0
from pycoin.key.validate import is_public_bip32_valid, is_address_valid
from pycoin.key.Key import Key
from pycoin.tx.tx_utils import create_signed_tx
from pycoin.tx.pay_to import ScriptMultisig, address_for_pay_to_script
from pycoin.encoding import EncodingError

from graphos.sources.model import ModelDataSource
from graphos.renderers import flot

from os import system
from decimal import Decimal
from urllib2 import urlopen

#region Variables

master_public_key = Key.from_text('SECRET_EXTENDED_PUBLIC_KEY')
api_code = 'SECRET_BLOCKCHAIN.INFO_API_CODE'
chikun_address = '12LmXkeVmSL3nBrMMBCPcLw2Jt97G1W4gr'
hostname = 'blockchain.info'
confirmations = 1
vig = Decimal('0.02')
v_key = 'VERY_LONG_RANDOM_STRING'

#endregion


#########
# VIEWS #
#########
def home(request):
    #region GET
Beispiel #9
0
        pass

def parse_as_secret_exponent(s):
    v = parse_as_number(s)
    if v and v < secp256k1._r:
        return v

secret_exponent = parse_as_secret_exponent(secret)
if secret_exponent:
    privkey = Key(secret_exponent=secret_exponent)

if SEC_RE.match(secret):
    privkey = Key.from_sec(unhexlify(secret))
else:
    try: 
        privkey = Key.from_text(secret)
    except encoding.EncodingError:
        pass
    
# Define vars automatically from privkey (could be manually, if you had the values)
privkey_uncompressed = '%x' % privkey.secret_exponent()
pubkey_uncompressed = hexlify(privkey.sec(use_uncompressed=True))

##
# Prepare pubkey for encrypting
##

pubkey_bin_tmp = arithmetic.changebase(pubkey_uncompressed[2:], 16, 256, minlen=64)
pubkey_bin = '\x02\xca\x00 '+ pubkey_bin_tmp[:32] + '\x00 ' + pubkey_bin_tmp[32:]

# Optionally you can use unhexlify, but need to add '\x20' after '\x00'