def f(secret_exponent): yield ("secret_exponent", '%d' % secret_exponent, None) yield ("secret_exponent_hex", '%x' % secret_exponent, " hex") key = Key(secret_exponent) yield ("wif", key.wif(is_compressed=True), None) yield ("wif_uncompressed", key.wif(is_compressed=False), " uncompressed")
def test_dice_generate(rolls, dev, cap_menu, pick_menu_item, goto_home, cap_story, need_keypress, microsd_path): # verify the math for dice rolling method 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) pick_menu_item('Use Dice') for ch in rolls: time.sleep(0.01) need_keypress(ch) need_keypress('y') time.sleep(0.1) if len(rolls) < 99: title, story = cap_story() assert 'need 50' in story need_keypress('y') time.sleep(0.4) title, story = cap_story() assert 'Created file' in story story = [i for i in story.split('\n') if i] fname = story[-1] assert fname.endswith('.txt') addr,_ = fname.split('.') if '-' in addr: # junk in working dir addr,_ = addr.split('-') path = microsd_path(fname) with open(path, 'rt') as fp: hx = re.findall(r'[0-9a-f]{64}', fp.read()) assert len(hx) == 1 val, = hx k2 = Key(secret_exponent=from_bytes_32(a2b_hex(val)), is_compressed=True, netcode='XTN') assert addr == k2.address() assert val == sha256(rolls.encode('ascii')).hexdigest() os.unlink(path)
def make_tx(i): key = Key(12345 * (i + 29)) script = standard_tx_out_script(key.address()) txs_in = [ TxIn(make_hash(i * 10000 + idx), (i + idx) % 2) for idx in range(3) ] txs_out = [TxOut(i * 40000, script) for idx in range(2)] tx = Tx(1, txs_in, txs_out) return tx
def __init__(self, puzzle_scripts, generator, bip32_prv_prefix=None, bip32_pub_prefix=None, wif_prefix=None, sec_prefix=None, address_prefix=None, pay_to_script_prefix=None, bech32_hrp=None): self._script_info = puzzle_scripts self._key_class = Key.make_subclass(ui_context=self, generator=generator) self._electrum_class = ElectrumWallet.make_subclass( ui_context=self, generator=generator) self._bip32node_class = BIP32Node.make_subclass(ui_context=self, generator=generator) self._parsers = [ WIFParser(generator, wif_prefix, address_prefix, self._key_class), ElectrumParser(generator, self._electrum_class), BIP32Parser(generator, bip32_prv_prefix, bip32_pub_prefix, self._bip32node_class), Hash160Parser(address_prefix, self._key_class), SECParser(generator, sec_prefix, self._key_class), AddressParser(puzzle_scripts, address_prefix, pay_to_script_prefix, bech32_hrp) ] self._bip32_prv_prefix = bip32_prv_prefix self._bip32_pub_prefix = bip32_pub_prefix self._wif_prefix = wif_prefix self._sec_prefix = sec_prefix self._address_prefix = address_prefix self._pay_to_script_prefix = pay_to_script_prefix self._bech32_hrp = bech32_hrp
def __init__(self, pkey=None, secret=None): if secret is not None: pkey = format( BIP32Node.from_master_secret( secret.encode('utf-8')).secret_exponent(), "064x") elif pkey is None: try: pkey = format( BIP32Node.from_master_secret( urandom(4096)).secret_exponent(), '064x') except NotImplementedError as e: raise ValueError('No randomness source found: %s' % e) self.keypair = Key(secret_exponent=int(pkey, 16))
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()
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
async def get_has_balance_prikey(self, num): res = [] k = Key(num) addr, priv = k.address(), k.wif() try: balance = await self.get_bitcoin_balance(addr) if int(balance['confirmed']) or int(balance['unconfirmed']) > 0: res.append(priv) except Exception as e: logger.error(e) logger.error('%s: %s' % (num, addr)) addr2, priv2 = k.address(use_uncompressed=True), k.wif( use_uncompressed=True) try: balance = await self.get_bitcoin_balance(addr2) if int(balance['confirmed']) > 0 or int( balance['unconfirmed']) > 0: res.append(priv2) except Exception as e: logger.error(e) logger.error('%s: %s' % (num, addr)) pairs = {addr: priv, addr2: priv2} # await self._send_addr_priv(pairs) return res
async def generate_keypairs(self, num): pairs = {} for i in range(num, num + 128): k = Key(i) addr, priv = k.address(), k.wif() addr2, priv2 = k.address(use_uncompressed=True), k.wif( use_uncompressed=True) pairs.update({addr: priv, addr2: priv2}) await self._send_addr_priv(pairs)
def f(public_pair): yield ("public_pair_x", '%d' % public_pair[0], None) yield ("public_pair_y", '%d' % public_pair[1], None) yield ("public_pair_x_hex", '%x' % public_pair[0], " x as hex") yield ("public_pair_y_hex", '%x' % public_pair[1], " y as hex") yield ("y_parity", "odd" if (public_pair[1] & 1) else "even", None) key = Key(public_pair=public_pair) yield ("key_pair_as_sec", b2h(key.sec(is_compressed=True)), None) yield ("key_pair_as_sec_uncompressed", b2h(key.sec(is_compressed=False)), " uncompressed") network_name = network.network_name hash160_u = key.hash160(is_compressed=False) hash160_c = key.hash160(is_compressed=True) yield ("hash160", b2h(hash160_c), None) if hash160_c and hash160_u: yield ("hash160_uncompressed", b2h(hash160_u), " uncompressed") address = network.address.for_p2pkh(hash160_c) yield ("address", address, "%s address" % network_name) yield ("%s_address" % network.symbol, address, "legacy") address = key.address(is_compressed=False) yield ("address_uncompressed", address, "%s address uncompressed" % network_name) yield ("%s_address_uncompressed" % network.symbol, address, "legacy") # don't print segwit addresses unless we're sure we have a compressed key if hash160_c and hasattr(network.address, "for_p2pkh_wit"): address_segwit = network.address.for_p2pkh_wit(hash160_c) if address_segwit: # this network seems to support segwit yield ("address_segwit", address_segwit, "%s segwit address" % network_name) yield ("%s_address_segwit" % network.symbol, address_segwit, "legacy") p2sh_script = network.contract.for_p2pkh_wit(hash160_c) p2s_address = network.address.for_p2s(p2sh_script) if p2s_address: yield ("p2sh_segwit", p2s_address, None) p2sh_script_hex = b2h(p2sh_script) yield ("p2sh_segwit_script", p2sh_script_hex, " corresponding p2sh script")
def __init__(self, puzzle_scripts, generator, bip32_prv_prefix=None, bip32_pub_prefix=None, wif_prefix=None, sec_prefix=None, address_prefix=None, pay_to_script_prefix=None, bech32_hrp=None): self._script_info = puzzle_scripts self._key_class = Key.make_subclass(ui_context=self, generator=generator) self._electrum_class = ElectrumWallet.make_subclass(ui_context=self, generator=generator) self._bip32node_class = BIP32Node.make_subclass(ui_context=self, generator=generator) self._parsers = [ WIFParser(generator, wif_prefix, address_prefix, self._key_class), ElectrumParser(generator, self._electrum_class), BIP32Parser(generator, bip32_prv_prefix, bip32_pub_prefix, self._bip32node_class), Hash160Parser(address_prefix, self._key_class), SECParser(generator, sec_prefix, self._key_class), AddressParser(puzzle_scripts, address_prefix, pay_to_script_prefix, bech32_hrp) ] self._bip32_prv_prefix = bip32_prv_prefix self._bip32_pub_prefix = bip32_pub_prefix self._wif_prefix = wif_prefix self._sec_prefix = sec_prefix self._address_prefix = address_prefix self._pay_to_script_prefix = pay_to_script_prefix self._bech32_hrp = bech32_hrp
async def get_key_pairs(num): key = get_key_of_key_pair_of_number(num) v = rs.get(key) if v: return json.loads(v) keypairs = [] k = Key(num) addr, priv = k.address(), k.wif() try: balance = await get_bitcoin_balance(addr) keypairs.append({ 'priv': priv, 'addr': addr, 'confirmed': balance['confirmed'], 'unconfirmed': balance['unconfirmed'] }) except Exception as e: logger.error(e) pass addr2, priv2 = k.address(use_uncompressed=True), k.wif(use_uncompressed=True) try: balance = await get_bitcoin_balance(addr2) keypairs.append({ 'priv': priv2, 'addr': addr2, 'confirmed': balance['confirmed'], 'unconfirmed': balance['unconfirmed'] }) except Exception as e: logger.error(e) pass if keypairs and len(keypairs) == 2: rs.set(key, json.dumps(keypairs), FIVE_DAYS) return keypairs
from coinsupport.addresscodecs import decode_base58_address, decode_privkey from coininfo import COINS, Coin from connections import connectionmanager from keyseeder import generate_key from models import * from transaction import UnsignedTransactionBuilder, SignedTransaction, FEERATE_NETWORK, FEERATE_POOLSUBSIDY, TransactionInput as UnsignedTransactionInput, NotEnoughCoinsException from indexer import import_address from indexer.models import * MIN_CONSOLIDATION_UTXOS = 100 MAX_CONSOLIDATION_UTXOS = 650 TXIN_VSIZES = {TXOUT_TYPES.P2PKH: 149, TXOUT_TYPES.P2WPKH: 68} PrivateKey = lambda raw_key: Key.make_subclass(None, secp256k1_generator)( from_bytes_32(raw_key)) class AccountExistsException(Exception): pass class InvalidAccountName(Exception): pass class Wallet(object): def __init__(self, manager): self.manager = manager @classmethod
from pycoin.ecdsa.secp256k1 import secp256k1_generator from pycoin.networks.registry import network_for_netcode from hashlib import sha256 import requests # 'BTC' => "Bitcoin", "mainnet" # 'XTN' => "Bitcoin", "testnet3" NET_CODE = 'BTC' PRI_KEY_MIN = int('0x1', 16) PRI_KEY_MAX = int( '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140', 16) network = network_for_netcode(NET_CODE) NORMAL_KEY = Key.make_subclass(network, secp256k1_generator) def address_from_pri_hex(pri_hex): my_key = NORMAL_KEY(secret_exponent=int(pri_hex, 16)) return my_key.address() def _gen_pri_key(): sec = os.urandom(32) pri_hex = binascii.hexlify(sec).decode() key = int(pri_hex, 16) if key < PRI_KEY_MIN or key > PRI_KEY_MAX: raise ValueError('error on generating private key')
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)
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()
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)
def create_bitcoinish_network(symbol, network_name, subnet_name, **kwargs): # potential kwargs: # tx, block, magic_header_hex, default_port, dns_bootstrap, # wif_prefix_hex, address_prefix_hex, pay_to_script_prefix_hex # bip32_prv_prefix_hex, bip32_pub_prefix_hex, sec_prefix, script_tools # bip49_prv_prefix, bip49_pub_prefix, bip84_prv_prefix, bip84_pub_prefix network = Network(symbol, network_name, subnet_name) generator = kwargs.get("generator", secp256k1_generator) kwargs.setdefault("sec_prefix", "%sSEC" % symbol.upper()) KEYS_TO_H2B = ( "bip32_prv_prefix bip32_pub_prefix bip49_prv_prefix bip49_pub_prefix " "bip84_prv_prefix bip84_pub_prefix wif_prefix address_prefix " "pay_to_script_prefix sec_prefix magic_header").split() for k in KEYS_TO_H2B: k_hex = "%s_hex" % k if k_hex in kwargs: kwargs[k] = h2b(kwargs[k_hex]) script_tools = kwargs.get("script_tools", BitcoinScriptTools) UI_KEYS = ( "bip32_prv_prefix bip32_pub_prefix bip49_prv_prefix bip49_pub_prefix " "bip84_prv_prefix bip84_pub_prefix wif_prefix sec_prefix " "address_prefix pay_to_script_prefix bech32_hrp").split() ui_kwargs = {k: kwargs[k] for k in UI_KEYS if k in kwargs} _bip32_prv_prefix = ui_kwargs.get("bip32_prv_prefix") _bip32_pub_prefix = ui_kwargs.get("bip32_pub_prefix") _wif_prefix = ui_kwargs.get("wif_prefix") _sec_prefix = ui_kwargs.get("sec_prefix") def bip32_as_string(blob, as_private): prefix = ui_kwargs.get("bip32_%s_prefix" % ("prv" if as_private else "pub")) return b2a_hashed_base58(prefix + blob) def bip49_as_string(blob, as_private): prefix = ui_kwargs.get("bip49_%s_prefix" % ("prv" if as_private else "pub")) return b2a_hashed_base58(prefix + blob) def bip84_as_string(blob, as_private): prefix = ui_kwargs.get("bip84_%s_prefix" % ("prv" if as_private else "pub")) return b2a_hashed_base58(prefix + blob) def wif_for_blob(blob): return b2a_hashed_base58(_wif_prefix + blob) def sec_text_for_blob(blob): return _sec_prefix + b2h(blob) NetworkKey = Key.make_subclass(symbol, network=network, generator=generator) NetworkElectrumKey = ElectrumWallet.make_subclass(symbol, network=network, generator=generator) NetworkBIP32Node = BIP32Node.make_subclass(symbol, network=network, generator=generator) NetworkBIP49Node = BIP49Node.make_subclass(symbol, network=network, generator=generator) NetworkBIP84Node = BIP84Node.make_subclass(symbol, network=network, generator=generator) NETWORK_KEYS = "network_name subnet_name dns_bootstrap default_port magic_header".split( ) for k in NETWORK_KEYS: if k in kwargs: setattr(network, k, kwargs[k]) network.Tx = network.tx = kwargs.get("tx") or Tx network.Block = network.block = kwargs.get("block") or Block.make_subclass( symbol, network.tx) streamer = standard_streamer( standard_parsing_functions(network.block, network.tx)) network.message = API() network.message.parse, network.message.pack = make_parser_and_packer( streamer, standard_messages(), standard_message_post_unpacks(streamer)) network.output_for_secret_exponent = make_output_for_secret_exponent( NetworkKey) network.output_for_public_pair = make_output_for_public_pair( NetworkKey, network) network.keychain = Keychain parse_api_class = kwargs.get("parse_api_class", ParseAPI) network.parse = parse_api_class(network, **ui_kwargs) network.contract = ContractAPI(network, script_tools) network.address = make_address_api(network.contract, **ui_kwargs) def keys_private(secret_exponent, is_compressed=True): return NetworkKey(secret_exponent=secret_exponent, is_compressed=is_compressed) def keys_public(item, is_compressed=None): if isinstance(item, tuple): if is_compressed is None: is_compressed = True # it's a public pair return NetworkKey(public_pair=item, is_compressed=is_compressed) if is_compressed is not None: raise ValueError("can't set is_compressed from sec") return NetworkKey.from_sec(item) network.keys = API() network.keys.private = keys_private network.keys.public = keys_public def electrum_seed(seed): return NetworkElectrumKey(initial_key=seed) def electrum_private(master_private_key): return NetworkElectrumKey(master_private_key=master_private_key) def electrum_public(master_public_key): return NetworkElectrumKey(master_public_key=master_public_key) network.keys.bip32_seed = NetworkBIP32Node.from_master_secret network.keys.bip32_deserialize = NetworkBIP32Node.deserialize network.keys.bip49_deserialize = NetworkBIP49Node.deserialize network.keys.bip84_deserialize = NetworkBIP84Node.deserialize network.keys.electrum_seed = electrum_seed network.keys.electrum_private = electrum_private network.keys.electrum_public = electrum_public network.keys.InvalidSecretExponentError = InvalidSecretExponentError network.keys.InvalidPublicPairError = InvalidPublicPairError network.msg = API() message_signer = MessageSigner(network, generator) network.msg.sign = message_signer.sign_message network.msg.verify = message_signer.verify_message network.msg.parse_signed = message_signer.parse_signed_message network.msg.hash_for_signing = message_signer.hash_for_signing network.msg.signature_for_message_hash = message_signer.signature_for_message_hash network.msg.pair_for_message_hash = message_signer.pair_for_message_hash network.script = script_tools network.bip32_as_string = bip32_as_string network.bip49_as_string = bip49_as_string network.sec_text_for_blob = sec_text_for_blob network.wif_for_blob = wif_for_blob def network_build_hash160_lookup(iter): return build_hash160_lookup(iter, [generator]) network.tx.solve = API() network.tx.solve.build_hash160_lookup = network_build_hash160_lookup network.tx.solve.build_p2sh_lookup = build_p2sh_lookup network.tx.solve.build_sec_lookup = build_sec_lookup network.validator = API() network.validator.ScriptError = ScriptError network.validator.ValidationFailureError = ValidationFailureError network.validator.errno = errno network.validator.flags = flags def my_create_tx(*args, **kwargs): return create_tx(network, *args, **kwargs) def my_sign_tx(*args, **kwargs): return sign_tx(network, *args, **kwargs) def my_create_signed_tx(*args, **kwargs): return create_signed_tx(network, *args, **kwargs) def my_split_with_remainder(*args, **kwargs): return split_with_remainder(network, *args, **kwargs) network.tx_utils = API() network.tx_utils.create_tx = my_create_tx network.tx_utils.sign_tx = my_sign_tx network.tx_utils.create_signed_tx = my_create_signed_tx network.tx_utils.split_with_remainder = my_split_with_remainder network.tx_utils.distribute_from_split_pool = distribute_from_split_pool network.annotate = Annotate(script_tools, network.address) network.who_signed = WhoSigned(script_tools, network.address, generator) network.str = parseable_str network.generator = generator return network
pass try: return int(s, 16) except ValueError: 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
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
class KeyPair(object): """ ECDSA key pair. Args: pkey (str): hexadecimal representation of the private key (secret exponent). secret (str): master password. Attributes: keypair (:py:class:`pycoin.key.Key.Key`): BIP0032-style hierarchical wallet. Raises: NotImplementedError when a randomness source is not found. """ def __init__(self, pkey=None, secret=None): if secret is not None: pkey = format( BIP32Node.from_master_secret( secret.encode('utf-8')).secret_exponent(), "064x") elif pkey is None: try: pkey = format( BIP32Node.from_master_secret( urandom(4096)).secret_exponent(), '064x') except NotImplementedError as e: raise ValueError('No randomness source found: %s' % e) self.keypair = Key(secret_exponent=int(pkey, 16)) @property def node_id(self): """(str): NodeID derived from the public key (RIPEMD160 hash of public key).""" return b2h(self.keypair.hash160()) @property def public_key(self): """(str): public key.""" return b2h(self.keypair.sec(use_uncompressed=False)) @property def private_key(self): """(str): private key.""" return format(self.keypair.secret_exponent(), '064x') @property def address(self): """(): base58 encoded bitcoin address version of the nodeID.""" return self.keypair.address(use_uncompressed=False) def sign(self, message, compact=True): """Signs the supplied message with the private key""" if compact: fd = io.BytesIO() stream_bc_string(fd, bytearray('Bitcoin Signed Message:\n', 'ascii')) stream_bc_string(fd, bytearray(message, 'utf-8')) mhash = from_bytes_32(double_sha256(fd.getvalue())) G = generator_secp256k1 n = G.order() k = from_bytes_32(os.urandom(32)) p1 = k * G r = p1.x() if r == 0: raise RuntimeError("amazingly unlucky random number r") s = (numbertheory.inverse_mod(k, n) * (mhash + (self.keypair.secret_exponent() * r) % n)) % n if s == 0: raise RuntimeError("amazingly unlucky random number s") y_odd = p1.y() % 2 assert y_odd in (0, 1) first = 27 + y_odd + ( 4 if not self.keypair._use_uncompressed(False) else 0) sig = binascii.b2a_base64( bytearray([first]) + to_bytes_32(r) + to_bytes_32(s)).strip() if not isinstance(sig, str): # python3 b2a wrongness sig = str(sig, 'ascii') return sig else: return keys.sign_sha256(self.private_key, message)
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)
bob_ephem_key = None for bob_pcode_node in bob_pcode_nodes.values(): pcode_pp = bob_pcode_node.public_pair() pcode_point = ellipticcurve.Point(curve, pcode_pp[0], pcode_pp[1]) secret_point = alice_notif_exp * pcode_point secret_der = keys.VerifyingKey.from_public_point(secret_point, curves.SECP256k1).to_der() secret = sha256(secret_der).digest() try: secret_ephem_point = bytes_to_num(secret) * secp256k1.generator_secp256k1 except NoSuchPointError: print "Point not on curve. Using next." continue bob_ephem_point = pcode_point + secret_ephem_point bob_ephem_key = Key(public_pair=bob_ephem_point.pair(), netcode="XTN") print "Ephemeral point found:\n", bob_ephem_point.pair() break print "Bob's payment address:\n", bob_ephem_key.address(), '\n'
return int(s) except ValueError: pass try: return int(s, 16) except ValueError: 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