Example #1
0
    def test_segwit_create_tx(self):
        from pycoin.tx.tx_utils import create_tx, sign_tx
        from pycoin.tx.Spendable import Spendable
        from pycoin.tx.pay_to.ScriptPayToAddress import ScriptPayToAddress
        from pycoin.tx.pay_to.ScriptPayToAddressWit import ScriptPayToAddressWit
        from pycoin.tx.pay_to.ScriptPayToScriptWit import ScriptPayToScriptWit
        from pycoin.ui import address_for_pay_to_script_wit, script_obj_from_address
        key1 = Key(1)
        coin_value = 5000000
        script = ScriptPayToAddressWit(b'\0', key1.hash160()).script()
        tx_hash = b'\ee' * 32
        tx_out_index = 0
        spendable = Spendable(coin_value, script, tx_hash, tx_out_index)
        key2 = Key(2)
        tx = create_tx([spendable], [(key2.address(), coin_value)])
        self.check_unsigned(tx)
        sign_tx(tx, [key1.wif()])
        self.check_signed(tx)
        self.assertEqual(len(tx.txs_in[0].witness), 2)

        s1 = ScriptPayToAddress(key1.hash160()).script()
        address = address_for_pay_to_script_wit(s1)
        spendable.script = script_obj_from_address(address).script()
        tx = create_tx([spendable], [(key2.address(), coin_value)])
        self.check_unsigned(tx)
        sign_tx(tx, [key1.wif()], p2sh_lookup=build_p2sh_lookup([s1]))
        self.check_signed(tx)
Example #2
0
    def test_segwit_create_tx(self):
        from pycoin.tx.tx_utils import create_tx, sign_tx
        from pycoin.tx.Spendable import Spendable
        from pycoin.tx.pay_to.ScriptPayToAddress import ScriptPayToAddress
        from pycoin.tx.pay_to.ScriptPayToAddressWit import ScriptPayToAddressWit
        from pycoin.tx.pay_to.ScriptPayToScriptWit import ScriptPayToScriptWit
        from pycoin.ui import address_for_pay_to_script_wit, script_obj_from_address
        key1 = Key(1)
        coin_value = 5000000
        script = ScriptPayToAddressWit(b'\0', key1.hash160()).script()
        tx_hash = b'\ee' * 32
        tx_out_index = 0
        spendable = Spendable(coin_value, script, tx_hash, tx_out_index)
        key2 = Key(2)
        tx = create_tx([spendable], [(key2.address(), coin_value)])
        self.check_unsigned(tx)
        sign_tx(tx, [key1.wif()])
        self.check_signed(tx)
        self.assertEqual(len(tx.txs_in[0].witness), 2)

        s1 = ScriptPayToAddress(key1.hash160()).script()
        address = address_for_pay_to_script_wit(s1)
        spendable.script = script_obj_from_address(address).script()
        tx = create_tx([spendable], [(key2.address(), coin_value)])
        self.check_unsigned(tx)
        sign_tx(tx, [key1.wif()], p2sh_lookup=build_p2sh_lookup([s1]))
        self.check_signed(tx)
Example #3
0
    def test_is_wif_valid(self):
        WIFS = [
            "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn",
            "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf",
            "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU74NMTptX4",
            "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAvUcVfH"
        ]

        for wif in WIFS:
            self.assertEqual(is_wif_valid(wif), "BTC")
            a = wif[:-1] + chr(ord(wif[-1]) + 1)
            self.assertEqual(is_wif_valid(a), None)

        NETWORK_NAMES = network_codes()
        for netcode in NETWORK_NAMES:
            for se in range(1, 10):
                key = Key(secret_exponent=se, netcode=netcode)
                for tv in [True, False]:
                    wif = key.wif(use_uncompressed=tv)
                    self.assertEqual(
                        is_wif_valid(wif, allowable_netcodes=[netcode]),
                        netcode)
                    a = wif[:-1] + chr(ord(wif[-1]) + 1)
                    self.assertEqual(
                        is_wif_valid(a, allowable_netcodes=[netcode]), None)
Example #4
0
def gen_key_pair_as_wif():
    key, pri_hex = _gen_pri_key()

    my_key = Key(secret_exponent=key,
                 prefer_uncompressed=False,
                 netcode=NET_CODE)

    return my_key.wif(), my_key.address()
Example #5
0
    def test_repr(self):
        key = Key(secret_exponent=273, netcode='XTN')

        address = key.address()
        pub_k = Key.from_text(address)
        self.assertEqual(repr(pub_k),  '<mhDVBkZBWLtJkpbszdjZRkH1o5RZxMwxca>')

        wif = key.wif()
        priv_k = Key.from_text(wif)
        self.assertEqual(repr(priv_k), 'private_for <0264e1b1969f9102977691a40431b0b672055dcf31163897d996434420e6c95dc9>')
Example #6
0
    def test_repr(self):
        key = Key(secret_exponent=273, netcode='XTN')

        address = key.address()
        pub_k = Key.from_text(address)
        self.assertEqual(repr(pub_k), '<mhDVBkZBWLtJkpbszdjZRkH1o5RZxMwxca>')

        wif = key.wif()
        priv_k = Key.from_text(wif)
        self.assertEqual(
            repr(priv_k),
            'private_for <0264e1b1969f9102977691a40431b0b672055dcf31163897d996434420e6c95dc9>'
        )
Example #7
0
def gen_2of3_multisig_key_pair():
    key_pairs = []
    for i in range(0, 3):
        key, pri_hex = _gen_pri_key()
        my_key = Key(secret_exponent=key,
                     prefer_uncompressed=False,
                     netcode=NET_CODE)

        # return wif or hex format, use your own strategy
        key_pairs.append((my_key.wif(), my_key.sec_as_hex()))

    return get_multisig_address(
        2, [binascii.unhexlify(key[1]) for key in key_pairs]), key_pairs
Example #8
0
    def test_repr(self):
        from pycoin.key import Key
        netcode = 'XTN'
        key = Key(secret_exponent=273, netcode=netcode)
        wallet = BIP32Node.from_master_secret(bytes(key.wif().encode('ascii')), netcode)

        address = wallet.address()
        pub_k = wallet.from_text(address)
        self.assertEqual(repr(pub_k),  '<myb5gZNXePNf2E2ksrjnHRFCwyuvt7oEay>')

        wif = wallet.wif()
        priv_k = wallet.from_text(wif)
        self.assertEqual(repr(priv_k), 'private_for <03ad094b1dc9fdce5d3648ca359b4e210a89d049532fdd39d9ccdd8ca393ac82f4>')
Example #9
0
	def _gen (self):
		logger.debug ('Generating entropy for new wallet...')

		# Generate entropy
		entropy = bytearray()
		try:
			entropy.extend(open("/dev/random", "rb").read(64))
		except Exception:
			print("warning: can't use /dev/random as entropy source")
		entropy = bytes(entropy)

		if len(entropy) < 64:
			raise OSError("can't find sources of entropy")

		secret_exponent = int(binascii.hexlify (entropy)[0:32], 16)
		wif = secret_exponent_to_wif(secret_exponent, compressed=True, wif_prefix=wif_prefix_for_netcode (self.chain))
		key = Key (secret_exponent=secret_exponent, netcode=self.chain)
		return (str (key.address ()), str (key.wif ()))
Example #10
0
    def test_is_wif_valid(self):
        WIFS = ["KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn",
                "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf",
                "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU74NMTptX4",
                "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAvUcVfH"]

        for wif in WIFS:
            self.assertEqual(is_wif_valid(wif), "BTC")
            a = wif[:-1] + chr(ord(wif[-1])+1)
            self.assertEqual(is_wif_valid(a), None)

        for netcode in NETWORK_NAMES:
            for se in range(1, 10):
                key = Key(secret_exponent=se, netcode=netcode)
                for tv in [True, False]:
                    wif = key.wif(use_uncompressed=tv)
                    self.assertEqual(is_wif_valid(wif, allowable_netcodes=[netcode]), netcode)
                    a = wif[:-1] + chr(ord(wif[-1])+1)
                    self.assertEqual(is_wif_valid(a, allowable_netcodes=[netcode]), None)
Example #11
0
def generatePrivateKey(seed, net="XTN"):
    """
    Generating a private key from any hexadecimal seed and net

    Args:
    -----
        seed: The seed to be used to generate the private key.
        net: The network to be used.

    Returns:
    --------
        The private key to be used.
    """
    # Generating the hexadecimal representation of the brainwallet
    key_bytes = hexlify(seed)
    # '68656c6c6f' for "hello"
    priv = Key(secret_exponent=int(codecs.encode(key_bytes, "hex"), 16),
               netcode=net)

    # Representation of the wallet
    print("\tSeed: " + seed)
    print("\tAddress: " + priv.address())
    print("\tWIF: " + priv.wif())
    return priv
Example #12
0
def secret_to_address(secret_exponent):
    k = Key(secret_exponent=secret_exponent)
    addr = k.address(use_uncompressed=True)
    caddr = k.address()
    wif = k.wif(use_uncompressed=True)
    return secret_exponent, wif, addr, caddr
Example #13
0
File: tx.py Project: xbee/icebox
print('Your Bitcoin address is...', address)
print('Your --privkey-bytes', hexlify(key_bytes).decode())

try:
    spendables = spendables_for_address(address, None)
    print('Spending', spendables)
except HTTPError as e:
    print(
        'Blockchain throws a 500 error if there are no spendables. Try sending some coins to',
        address, 'and try again. Remeber to copy privkey-bytes.')
    sys.exit()

tx = create_tx(spendables, [args.send_all_to])
print('TX created:', repr(tx))

sign_tx(tx, [private_key.wif(False), private_key.wif(True)])
print('Final TX:', tx)

# print('TX Send Attempt:', send_tx(tx))
'''
tx_in = TxIn("<utxo hash in binary here>", <utxo position, usually between 0 and 5>)
script = standard_tx_out_script(address)
tx_out = TxOut(<btc amount to send - fee>, script)
tx = Tx(1, [tx_in], [tx_out])
lookup = <this part you have to figure out>
tx.sign(lookup)
print tx.as_hex()



def privateKeyToWif(key_hex):
Example #14
0
def register_page(request, refererUUID):
    getBtcPrice()
    price = sysvar.objects.get(pk=1)
    btcPrice = price.btcPrice
    counter = price.counter
    email_taken = False
    username_taken = False
    if request.user.is_authenticated():
        return render(request, 'home.html')
    registration_form = RegistrationForm()
    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():

            datas = {}
            if User.objects.filter(
                    username=form.cleaned_data['username']).exists():
                username_taken = True
                return render(
                    request, 'register_page.html', {
                        'form': registration_form,
                        'username_taken': username_taken,
                        'btcPrice': btcPrice
                    })
            elif User.objects.filter(
                    email=form.cleaned_data['email']).exists():
                email_taken = True
                return render(
                    request, 'register_page.html', {
                        'form': registration_form,
                        'email_taken': email_taken,
                        'btcPrice': btcPrice
                    })
            datas['username'] = form.cleaned_data['username']
            datas['email'] = form.cleaned_data['email']
            datas['password1'] = form.cleaned_data['password1']
            datas['referer'] = refererUUID
            #We will generate a random activation key
            s = 'xprv9s21ZrQH143K2Lap6SnULZfdEi4ivcbottMVoY7MaupCQhVLfARkygyW9N7PKsBSPd2gTQXZr1R4iqkLCQ3TUxvs9NvwYRScCVGV8Aos7ad'
            mykey = Key.from_text(s)
            mysub = mykey.subkey(counter)
            address = Key.address(mysub)
            wif = Key.wif(mysub)
            datas['deposit_add'] = address
            datas['wif'] = wif
            price.counter = price.counter + 1
            price.save()
            salt = hashlib.sha1(str(
                random.random()).encode('utf-8')).hexdigest()[:5]
            usernamesalt = datas['email']

            if isinstance(usernamesalt, str):
                usernamesalt = str.encode(usernamesalt)
            if isinstance(salt, str):
                salt = str.encode(salt)
            print(salt)
            print(usernamesalt)
            datas['activation_key'] = hashlib.sha1(salt +
                                                   usernamesalt).hexdigest()

            datas[
                'email_path'] = "/home/connell-gough/django/bl4btc/btc/static/ActivationEmail.txt"
            datas['email_subject'] = "activate your account"

            form.sendEmail(datas)  #Send validation email
            form.save(datas)  #Save the user and his profile

            request.session['registered'] = True  #For display purposes
            return render(request, 'register_page.html', {
                'email_sent': True,
                'btcPrice': btcPrice
            })
        else:

            registration_form = form  #Display form with error messages (incorrect fields, etc)

    return render(
        request, 'register_page.html', {
            'form': registration_form,
            'btcPrice': btcPrice,
            'refererUUID': refererUUID
        })
Example #15
0
def secret_to_address(secret_exponent):
    k = Key(secret_exponent=secret_exponent)
    addr = k.address(use_uncompressed=True)
    caddr = k.address()
    wif = k.wif(use_uncompressed=True)
    return secret_exponent, wif, addr, caddr
Example #16
0
from pycoin.key import Key
from pycoin.serialize import h2b
from pycoin.tx import Tx, TxIn, TxOut, SIGHASH_ALL, tx_utils
from pycoin.tx.TxOut import standard_tx_out_script

from pycoin.tx.pay_to import ScriptMultisig, ScriptPayToPublicKey
from pycoin.tx.pay_to import address_for_pay_to_script, build_hash160_lookup, build_p2sh_lookup
from pycoin.tx.pay_to import script_obj_from_address, script_obj_from_script

publicaddress = "mkR94WCqr4gpZauH8ieTLTG6jkZ2uBB6SA"
wif = "cUDx8gXXBZRePmm46LSZetbWqNwXBmm3WQziGVykAgL8NJKMRjQR"

key = Key.from_text(publicaddress)

key = Key(secret_exponent=1)
print key.address()
print key.wif()
print key.secret_exponent()
Example #17
0
from pycoin.key import Key, BIP32Node

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--netcode",
                    type=str,
                    required=True,
                    help='netcode: BTC/LTC/XTN/...')
parser.add_argument("--target", type=str, required=True, help='to address')
args = parser.parse_args()

to_address = args.target
private_key = 'YOUR PRIVATE KEY'
the_key = Key(secret_exponent=int(private_key, 16))
master_key = BIP32Node.BIP32Node.from_master_secret(
    bytes(the_key.wif().encode('ascii')), args.netcode)
from_address = master_key.address()


# that's work for insight
# TODO: 设计通用utxo
def get_speendable(address):
    URL = "%s%saddr/%s/utxo" % ('https://test-insight.bitpay.com', '/api/',
                                from_address)
    utxos = json.loads(urlopen(URL).read().decode("utf8"))

    utxo = utxos[0]

    return Spendable(utxo['amount'], h2b(utxo.get("scriptPubKey")),
                     h2b_rev(utxo.get("txid")), utxo.get("vout"))
Example #18
0
privkey_hex = b2h(encoding.to_bytes_32(my_key.secret_exponent()))
assert(len(privkey_hex) == 64)

print("\npycoin.key.Key example - ", my_netcode)

#print("Private Key (dec): ", eval('0x' + privkey_hex))
print("Private Key (dec): ", int(privkey_hex, 16))
print("Private Key (hex): ", privkey_hex)
privkey_bytes = unhexlify(privkey_hex)
# use CBitcoinSecret to compress private key
btc_secret = CBitcoinSecret.from_secret_bytes(privkey_bytes, True)
print("     compressed: ", hexlify(btc_secret.to_bytes()))
assert(btc_secret.is_compressed == True)
assert(bitcoin.core.b2x(btc_secret.to_bytes()) == (privkey_hex + '01'))

print("Private Key   WIF: ", my_key.wif())
print("     uncompressed: ", my_key.wif(use_uncompressed=True))

print("Privkey hashed base58: ", encoding.b2a_hashed_base58(privkey_bytes))


print()
## Public key and address
public_key = my_key.public_pair()
(public_key_x, public_key_y) = public_key

print("Public Key Pair: ", public_key)
print("     x as hex: ", hex(public_key[0]))
print("     y as hex: ", hex(public_key[1]))

#compressed_indicator_1 = '02' if (public_key_y % 2) == 0 else '03'
Example #19
0
def main():
    parser = argparse.ArgumentParser(
        description='ECkey2coin.py by [email protected] for UTXO based Certificates UTXOC.',
        epilog='Known networks codes:\n  ' \
                + ', '.join(['%s (%s)'%(i, full_network_name_for_netcode(i)) for i in NETWORK_NAMES])
    )
    parser.add_argument('-k', '--key', required=False, type=argparse.FileType('r'), help='The EC private key in PEM format')
    parser.add_argument('-q', '--qrfilename', required=False, help='QR code output filename')
    parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)',
                                default='BTC', choices=NETWORK_NAMES)
    args = parser.parse_args()
    network = args.network
    inputprivatekey = ''
    if args.key:
        keyfile = args.key        
        while True:
            line = keyfile.readline().strip()
            if not line: break
            inputprivatekey += line + '\n'
        print 'Loaded EC Key from %s' % keyfile
    else:    
        print ('Please enter EC KEY in pem format:')
        inputprivatekey  = ''
        while True:
            line = raw_input().strip()
            if not line: break
            inputprivatekey += line + '\n'
    if not args.qrfilename:
        qrfilename = raw_input("Please enter qrcode output filename: ")
    else:
        qrfilename = args.qrfilename
    pkey = decoder.decode(read_pem(inputprivatekey), asn1Spec=ECPrivateKey())
    print 'Key loaded'
    if not isValidECKey(pkey[0]):
        print "EC Key Supplied cannot be used"
        exit
    print "Key Validated OK"
    inputkey = encoding.to_long(256, pycoin.encoding.byte_to_int, pkey[0][1].asOctets())[0]
    if inputkey:
        key = Key(secret_exponent=inputkey, netcode=network)
        btcsecret = key.secret_exponent()
        btcpublic = key.public_pair()
        hash160_c = key.hash160(use_uncompressed=False)
        hash160_u = key.hash160(use_uncompressed=True)
        qrimg = qrcode.QRCode (
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qrimg.add_data(key.address(use_uncompressed=False))
        qrimg.make(fit=True)
        img = qrimg.make_image()
        img.save(qrfilename)
    print"----------------- BEGIN EC PRIVATE KEYS -----------------"
    print "Secret:     %d" % btcsecret
    print "Secret hex: %x" % btcsecret
    print "wif:        %s" % key.wif(use_uncompressed=False)
    print "----------------- END EC PRIVATE KEYS -----------------------------"
    print "----------------- BEGIN PUBLIC KEY -----------------------------"
    print "Public X: %d" % btcpublic[0]
    print "Public Y: %d" % btcpublic[1]
    print "hash160 uncompressed: %s" % b2h(hash160_u)
    print "Sec: (uncompressed): %s" % b2h(key.sec(use_uncompressed=True))
    print "%s address: %s (uncompressed)" % (key._netcode, key.address(use_uncompressed=True))
    print "Public X (hex): %x" % btcpublic[0]
    print "Public Y (hex): %x" % btcpublic[1]
    print "Sec: %s" % b2h(key.sec(use_uncompressed=False))
    print "hash160 compressed: %s" % b2h(hash160_c)
    print "----------------- END PUBLIC KEYS -----------------------------"
    print "------------------ BEGIN %s ADDRESSES -------------------------" % key._netcode
    print "%s address: %s" % (key._netcode, key.address(use_uncompressed=False))
    print "------------------ END %s ADDRESSES -------------------------" % key._netcode