def __init__(self, model, config): """Create a deterministic wallet address manager given a wallet <model> and a configuration <config>. Note address manager configuration is in the key "hdwam". """ self.config = config self.testnet = config.get('testnet', False) self.model = model self.addresses = [] # initialize the wallet manager if this is the first time # this will generate a master key. params = config.get('hdwam', None) if params is None: params = self.init_new_wallet() # master key is stored in a separate config entry self.master_key = config['hdw_master_key'] master = hashlib.sha512(self.master_key.decode('hex')).digest() # initialize a BIP-0032 wallet self.pycoin_wallet = Wallet(is_private=True, is_test=self.testnet, chain_code=master[32:], secret_exponent_bytes=master[:32]) self.genesis_color_sets = params['genesis_color_sets'] self.color_set_states = params['color_set_states'] # import the genesis addresses for i, color_desc_list in enumerate(self.genesis_color_sets): addr = self.get_genesis_address(i) addr.color_set = ColorSet(self.model, color_desc_list) self.addresses.append(addr) # now import the specific color addresses for color_set_st in self.color_set_states: color_desc_list = color_set_st['color_set'] max_index = color_set_st['max_index'] color_set = ColorSet(self.model, color_desc_list) params = { 'testnet': self.testnet, 'pycoin_wallet': self.pycoin_wallet, 'color_set': color_set } for index in xrange(max_index + 1): params['index'] = index self.addresses.append(BIP0032AddressRecord(**params)) # import the one-off addresses from the config for addr_params in config.get('addresses', []): addr_params['testnet'] = self.testnet addr_params['model'] = model try: address = LooseAddressRecord(**addr_params) self.addresses.append(address) except InvalidAddressError: address_type = "Testnet" if self.testnet else "Bitcoin"
def private_key_iterator(pk): try: wallet = Wallet.from_wallet_key(pk) return (w.secret_exponent for w in wallet.children(max_level=50, start_index=0)) except (encoding.EncodingError, TypeError): try: exp = encoding.wif_to_secret_exponent(pk) return [exp] except encoding.EncodingError: sys.stderr.write('bad value: "%s"\n' % pk) sys.exit(1)
def getnewaddress(self, seed=""): if seed=="": seed = os.urandom(64) else: seed = seed.encode("utf8") entropy = bytearray(seed) pycwallet = PycoinWallet.from_master_secret(bytes(entropy), is_test=False) address = pycwallet.bitcoin_address() secret_exponent = hex(pycwallet.secret_exponent)[2:].encode('utf8') self.insertaddress(address, secret_exponent) return address
def get_info_do(chain_path, source_key, entropy, testnet): if(source_key == None and chain_path == None): if(entropy == None): return {'error': '"no_entropy"'} else: try: # Python 3 w = Wallet.from_master_secret(bytes(entropy, encoding='ascii'), is_test=testnet) return {'result': wallet_to_json(w)} except: # Python 2.7 w = Wallet.from_master_secret(bytes(entropy).encode('ascii'), is_test=testnet) return {'result': wallet_to_json(w)} elif(source_key == None): return {'error': '"no_source_key"'} else: w = Wallet.from_wallet_key(source_key) if(chain_path == None): return {'result': wallet_to_json(w)} else: return {'result': wallet_to_json(w.subkey_for_path(chain_path))} return {'error': '"unexpected (chain_path: "' + chain_path + '"; source_key: "' + source_key + '")"'}
def getnewaddress(self, seed=""): if seed == "": seed = os.urandom(64) else: seed = seed.encode("utf8") entropy = bytearray(seed) pycwallet = PycoinWallet.from_master_secret(bytes(entropy), is_test=False) address = pycwallet.bitcoin_address() secret_exponent = hex(pycwallet.secret_exponent)[2:].encode('utf8') self.insertaddress(address, secret_exponent) return address
def get_new_address(wallet_num): passphrase = sha256(b"%s" % random.randint(0, 2 ** 30)).hexdigest() wallet = Wallet.from_master_secret(passphrase) ret = dump_node(wallet) children = [] # Now build up some random paths # Just go five deep path = "m" for depth in range(5): child_number = random.randint(0, 0x80000000) path = "%s/%s" % (path, child_number) prime = random.choice([True, False]) if prime: path += "'" children.append({"path": path, "child": dump_node(wallet.subkey_for_path(path[2:]))}) ret["children"] = children return ret
def get_new_address(wallet_num): passphrase = sha256(b"%s" % random.randint(0, 2**30)).hexdigest() wallet = Wallet.from_master_secret(passphrase) ret = dump_node(wallet) children = [] # Now build up some random paths # Just go five deep path = "m" for depth in range(5): child_number = random.randint(0, 0x80000000) path = "%s/%s" % (path, child_number) prime = random.choice([True, False]) if prime: path += "'" children.append( {"path": path, "child": dump_node(wallet.subkey_for_path(path[2:]))}) ret['children'] = children return ret
def main(): parser = argparse.ArgumentParser(description="Generate a private wallet key.") parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true') parser.add_argument('-i', "--info", help='show metadata', action='store_true') parser.add_argument('-j', "--json", help='output metadata as JSON', action='store_true') parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true') parser.add_argument('-f', "--wallet-key-file", help='initial wallet key', type=argparse.FileType('r')) parser.add_argument('-k', "--wallet-key", help='initial wallet key') parser.add_argument('-g', "--gpg", help='use gpg --gen-random to get additional entropy', action='store_true') parser.add_argument('-u', "--dev-random", help='use /dev/random to get additional entropy', action='store_true') parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true') parser.add_argument('-p', help='generate wallet key from passphrase. NOT RECOMMENDED', metavar='passphrase') parser.add_argument('-s', "--subkey", help='subkey path (example: 0p/2/1)') parser.add_argument('-t', help='generate test key', action="store_true") parser.add_argument('inputfile', help='source of entropy. stdin by default', type=argparse.FileType(mode='r+b'), nargs='?') args = parser.parse_args() # args.inputfile doesn't like binary when "-" is passed in. Deal with this. if args.inputfile == sys.stdin: args.inputfile = sys.stdin.buffer entropy = bytearray() if args.gpg: entropy.extend(gpg_entropy()) if args.dev_random: entropy.extend(dev_random_entropy()) if args.inputfile: entropy.extend(args.inputfile.read()) if args.p: entropy.extend(args.p.encode("utf8")) if len(entropy) == 0 and not args.wallet_key and not args.wallet_key_file: parser.error("you must specify at least one source of entropy") if args.wallet_key and len(entropy) > 0: parser.error("don't specify both entropy and a wallet key") if args.wallet_key_file: wallet = Wallet.from_wallet_key(args.wallet_key_file.readline()[:-1]) elif args.wallet_key: wallet = Wallet.from_wallet_key(args.wallet_key) else: wallet = Wallet.from_master_secret(bytes(entropy), is_test=args.t) try: if args.subkey: wallet = wallet.subkey_for_path(args.subkey) if args.json: print("{") print(' "wallet_key" : "%s",' % wallet.wallet_key(as_private=wallet.is_private)) if wallet.is_test: print(' "network" : "test",') else: print(' "network" : "main",') if wallet.is_private: print(' "key" : "private",') print(' "secret_exponent" : "%d",' % wallet.secret_exponent) else: print(' "key" : "public",') print(' "public_pair_x": "%d",\n "public_pair_y" : "%d",' % wallet.public_pair) print(' "tree_depth" : "%d",' % wallet.depth) print(' "fingerprint" : "%s",' % b2h(wallet.fingerprint())) print(' "parent_fingerprint" : "%s",' % b2h(wallet.parent_fingerprint)) if wallet.child_number >= 0x80000000: wc = wallet.child_number - 0x80000000 child_index = "%dp (%d)" % (wc, wallet.child_number) else: child_index = "%d" % wallet.child_number print(' "child_index": "%s",' % child_index) print(' "chain_code": "%s",' % b2h(wallet.chain_code)) if wallet.is_private: print(' "wif" : "%s",' % wallet.wif()) print(' "wif_uncompressed" : "%s",' % wallet.wif(compressed=False)) print(' "bitcoin_addr" : "%s",' % wallet.bitcoin_address()) print(' "bitcoin_addr_uncompressed": "%s"' % wallet.bitcoin_address(compressed=False)) print('}') elif args.info: print(wallet.wallet_key(as_private=wallet.is_private)) if wallet.is_test: print("test network") else: print("main network") if wallet.is_private: print("private key") print("secret exponent: %d" % wallet.secret_exponent) else: print("public key only") print("public pair x: %d\npublic pair y: %d" % wallet.public_pair) print("tree depth: %d" % wallet.depth) print("fingerprint: %s" % b2h(wallet.fingerprint())) print("parent f'print: %s" % b2h(wallet.parent_fingerprint)) if wallet.child_number >= 0x80000000: wc = wallet.child_number - 0x80000000 child_index = "%dp (%d)" % (wc, wallet.child_number) else: child_index = "%d" % wallet.child_number print("child index: %s" % child_index) print("chain code: %s" % b2h(wallet.chain_code)) if wallet.is_private: print("WIF: %s" % wallet.wif()) print(" uncompressed: %s" % wallet.wif(compressed=False)) print("Bitcoin address: %s" % wallet.bitcoin_address()) print(" uncompressed: %s" % wallet.bitcoin_address(compressed=False)) elif args.address: print(wallet.bitcoin_address(compressed=not args.uncompressed)) elif args.wif: print(wallet.wif(compressed=not args.uncompressed)) else: print(wallet.wallet_key(as_private=wallet.is_private)) except PublicPrivateMismatchError as ex: print(ex.args[0])
def wifPrivKeyToXpub(privKey): privWallet = Wallet.from_master_secret(privKey) return (privWallet.wallet_key(as_private=False), privWallet.wallet_key(as_private=True))
def genPrivateKeys(privKey, listOfPaths=[]): privWallet = Wallet.from_wallet_key(privKey) print '%5s | %s | %s' % ('path', 'wif', 'addr') for path in listOfPaths: print '%5s | %s | %s' % (path, privWallet.subkey_for_path(path).wif(), privWallet.subkey_for_path(path).bitcoin_address())
bitcoind = ServiceProxy(config["bitcoind_connection"]) # methodToCall = getattr(bitcoind, "getinfo") # methodToCall() chain_headers = leveldb.LevelDB('./chain_headers.db') chain_data = leveldb.LevelDB('./chain_data.db') LARGEST_POSSIBLE_SUBKEY = 2147483647 from pycoin.wallet import Wallet print "Enter wallet passphrase:", passphrase = raw_input() my_prv = Wallet.from_master_secret(passphrase) my_prv_key = my_prv.wallet_key(as_private=True) my_pub_key = my_prv.wallet_key(as_private=False) my_pub = Wallet.from_wallet_key(my_pub_key) print "Master pub key", my_pub_key try: master_pub_key = chain_headers.Get("pub_key") if master_pub_key != my_pub_key: raise Exception("Error: db master pub key differs from input key.") except KeyError: chain_headers.Put('pub_key', my_pub_key) try: master_pub_key = chain_data.Get("pub_key") if master_pub_key != my_pub_key:
try: #print "Would kill %s" % file_path if os.path.isfile(file_path): os.unlink(file_path) except Exception, e: pass j2_env = Environment(loader=FileSystemLoader(path), trim_blocks=True ) tmpl = j2_env.get_template('qrlayout.tmpl') tmpl_vars = { "outrows":[], "savedir": savepath, "funding_amount": funding_amount } row = [] coins_to = [] ###LEFT OFF HERE append the tuples ... satoshis,btcaddy (i think, see spend.py around line 39) for i in range(code_count): w = Wallet.from_master_secret(bytes(bytearray(open("/dev/urandom", "rb").read(64)))) wif = w.wif() btc_addr = w.bitcoin_address() coins_to.append((int(s_per_b*funding_amount), btc_addr)) print "Generating for version %s ... %s .. %s" % (i, wif, w.bitcoin_address()) qr = QRCode(border=0, box_size=10) qr.add_data(wif) im = qr.make_image(fit=True) im.save('%s/%s.png'%(savepath, btc_addr )) row.append({ 'address' : btc_addr }) if (((i+1) % code_per_row) == 0) or (i+1 == code_count): #print "NEW ROW ... (i+1 = %s, len(row) = %s, code_count = %s ... %s and %s)"%(i+1, len(row), code_count, (((i+1) % len(row)) == 0), (i+1 == code_count))
def main(): parser = argparse.ArgumentParser( description="Generate a private wallet key.") parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true') parser.add_argument('-i', "--info", help='show metadata', action='store_true') parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true') parser.add_argument('-f', "--wallet-key-file", help='initial wallet key', type=argparse.FileType('r')) parser.add_argument('-k', "--wallet-key", help='initial wallet key') parser.add_argument('-g', "--gpg", help='use gpg --gen-random to get additional entropy', action='store_true') parser.add_argument('-u', "--dev-random", help='use /dev/urandom to get additional entropy', action='store_true') parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true') parser.add_argument( '-p', help='generate wallet key from passphrase. NOT RECOMMENDED', metavar='passphrase') parser.add_argument('-s', "--subkey", help='subkey path (example: 0p/2/1)') parser.add_argument('-t', help='generate test key', action="store_true") parser.add_argument('inputfile', help='source of entropy. stdin by default', type=argparse.FileType(mode='r+b'), nargs='?') args = parser.parse_args() # args.inputfile doesn't like binary when "-" is passed in. Deal with this. if args.inputfile == sys.stdin: args.inputfile = sys.stdin.buffer entropy = bytearray() if args.gpg: entropy.extend(gpg_entropy()) if args.dev_random: entropy.extend(dev_random_entropy()) if args.inputfile: entropy.extend(args.inputfile.read()) if args.p: entropy.extend(args.p.encode("utf8")) if len(entropy) == 0 and not args.wallet_key and not args.wallet_key_file: parser.error("you must specify at least one source of entropy") if args.wallet_key and len(entropy) > 0: parser.error("don't specify both entropy and a wallet key") if args.wallet_key_file: wallet = Wallet.from_wallet_key(args.wallet_key_file.readline()[:-1]) elif args.wallet_key: wallet = Wallet.from_wallet_key(args.wallet_key) else: wallet = Wallet.from_master_secret(bytes(entropy), is_test=args.t) try: if args.subkey: wallet = wallet.subkey_for_path(args.subkey) if args.info: print(wallet.wallet_key(as_private=wallet.is_private)) if wallet.is_test: print("test network") else: print("main network") if wallet.is_private: print("private key") print("secret exponent: %d" % wallet.secret_exponent) else: print("public key only") print("public pair x: %d\npublic pair y: %d" % wallet.public_pair) print("tree depth: %d" % wallet.depth) print("fingerprint: %s" % b2h(wallet.fingerprint())) print("parent f'print: %s" % b2h(wallet.parent_fingerprint)) if wallet.child_number >= 0x80000000: wc = wallet.child_number - 0x80000000 child_index = "%dp (%d)" % (wc, wallet.child_number) else: child_index = "%d" % wallet.child_number print("child index: %s" % child_index) print("chain code: %s" % b2h(wallet.chain_code)) if wallet.is_private: print("WIF: %s" % wallet.wif()) print(" uncompressed: %s" % wallet.wif(compressed=False)) print("Bitcoin address: %s" % wallet.bitcoin_address()) print(" uncompressed: %s" % wallet.bitcoin_address(compressed=False)) elif args.address: print(wallet.bitcoin_address(compressed=not args.uncompressed)) elif args.wif: print(wallet.wif(compressed=not args.uncompressed)) else: print(wallet.wallet_key(as_private=wallet.is_private)) except PublicPrivateMismatchError as ex: print(ex.args[0])
def main(): parser = argparse.ArgumentParser(description="Generate a private wallet key.") parser.add_argument("-a", "--address", help="show as Bitcoin address", action="store_true") parser.add_argument("-i", "--info", help="show metadata", action="store_true") parser.add_argument("-j", "--json", help="output metadata as JSON", action="store_true") parser.add_argument("-w", "--wif", help="show as Bitcoin WIF", action="store_true") parser.add_argument("-f", "--wallet-key-file", help="initial wallet key", type=argparse.FileType("r")) parser.add_argument("-k", "--wallet-key", help="initial wallet key") parser.add_argument("-g", "--gpg", help="use gpg --gen-random to get additional entropy", action="store_true") parser.add_argument("-u", "--dev-random", help="use /dev/random to get additional entropy", action="store_true") parser.add_argument("-n", "--uncompressed", help="show in uncompressed form", action="store_true") parser.add_argument("-p", help="generate wallet key from passphrase. NOT RECOMMENDED", metavar="passphrase") parser.add_argument("-s", "--subkey", help="subkey path (example: 0p/2/1)") parser.add_argument("-t", help="generate test key", action="store_true") parser.add_argument( "inputfile", help="source of entropy. stdin by default", type=argparse.FileType(mode="r+b"), nargs="?" ) args = parser.parse_args() # args.inputfile doesn't like binary when "-" is passed in. Deal with this. if args.inputfile == sys.stdin: args.inputfile = sys.stdin.buffer entropy = bytearray() if args.gpg: entropy.extend(gpg_entropy()) if args.dev_random: entropy.extend(dev_random_entropy()) if args.inputfile: entropy.extend(args.inputfile.read()) if args.p: entropy.extend(args.p.encode("utf8")) if len(entropy) == 0 and not args.wallet_key and not args.wallet_key_file: parser.error("you must specify at least one source of entropy") if args.wallet_key and len(entropy) > 0: parser.error("don't specify both entropy and a wallet key") if args.wallet_key_file: wallet = Wallet.from_wallet_key(args.wallet_key_file.readline()[:-1]) elif args.wallet_key: wallet = Wallet.from_wallet_key(args.wallet_key) else: wallet = Wallet.from_master_secret(bytes(entropy), is_test=args.t) try: if args.subkey: wallet = wallet.subkey_for_path(args.subkey) if wallet.child_number >= 0x80000000: wc = wallet.child_number - 0x80000000 child_index = "%dp (%d)" % (wc, wallet.child_number) else: child_index = "%d" % wallet.child_number if args.json: d = dict( wallet_key=wallet.wallet_key(as_private=wallet.is_private), public_pair_x=wallet.public_pair[0], public_pair_y=wallet.public_pair[1], tree_depth=wallet.depth, fingerprint=b2h(wallet.fingerprint()), parent_fingerprint=b2h(wallet.parent_fingerprint), child_index=child_index, chain_code=b2h(wallet.chain_code), bitcoin_addr=wallet.bitcoin_address(), bitcoin_addr_uncompressed=wallet.bitcoin_address(compressed=False), network="test" if wallet.is_test else "main", ) if wallet.is_private: d.update( dict( key="private", secret_exponent=wallet.secret_exponent, WIF=wallet.wif(), WIF_uncompressed=wallet.wif(compressed=False), ) ) else: d.update(dict(key="public")) print(json.dumps(d, indent=3)) elif args.info: print(wallet.wallet_key(as_private=wallet.is_private)) if wallet.is_test: print("test network") else: print("main network") if wallet.is_private: print("private key") print("secret exponent: %d" % wallet.secret_exponent) else: print("public key only") print("public pair x: %d\npublic pair y: %d" % wallet.public_pair) print("tree depth: %d" % wallet.depth) print("fingerprint: %s" % b2h(wallet.fingerprint())) print("parent f'print: %s" % b2h(wallet.parent_fingerprint)) print("child index: %s" % child_index) print("chain code: %s" % b2h(wallet.chain_code)) if wallet.is_private: print("WIF: %s" % wallet.wif()) print(" uncompressed: %s" % wallet.wif(compressed=False)) print("Bitcoin address: %s" % wallet.bitcoin_address()) print(" uncompressed: %s" % wallet.bitcoin_address(compressed=False)) elif args.address: print(wallet.bitcoin_address(compressed=not args.uncompressed)) elif args.wif: print(wallet.wif(compressed=not args.uncompressed)) else: print(wallet.wallet_key(as_private=wallet.is_private)) except PublicPrivateMismatchError as ex: print(ex.args[0])
def PublicMasterFromSecretString(secretString): return Wallet.from_master_secret(secretString).public_copy().wallet_key()
def AddressFromPublicMasterAndSubkeyPath(publicMaster, subkeyPath): return Wallet.from_wallet_key(publicMaster).subkey_for_path(subkeyPath).bitcoin_address()
def generate_random_wallet(): entropy = bytearray(devrandom_entropy()) return Wallet.from_master_secret(bytes(entropy), is_test=False)
from datetime import datetime from django.conf import settings from pycoin.wallet import Wallet # The first derivation is for the month # Not used anymore, is always month 0 (more practical) SUBKEY_ALL_MONTHS = Wallet.from_wallet_key(settings.DONATIONS_WALLET_KEY).subkey_for_path('0') def donationsOrgSubKey(org_id): return SUBKEY_ALL_MONTHS.subkey_for_path('%d' % org_id) def donationsOrgAddress(org_id): return SUBKEY_ALL_MONTHS.subkey_for_path('%d' % org_id).bitcoin_address()
def PrivKeyFromSecretStringAndSubkeyPath(secretString, subkeyPath): return Wallet.from_master_secret(secretString).subkey_for_path( subkeyPath).bitcoin_address()
def AddressFromPublicMasterAndSubkeyPath(publicMaster, subkeyPath): return Wallet.from_wallet_key(publicMaster).subkey_for_path( subkeyPath).bitcoin_address()
short_name='p') gflags.MarkFlagAsRequired('password') gflags.DEFINE_integer('timeout', 15, u"Timeout for communication with RPC server, or zero to disable") gflags.RegisterValidator('timeout', lambda timeout: 0 <= timeout, message=u"Valid timeout setting must be a positive number of seconds, or zero.") gflags.DEFINE_boolean('testnet', False, u"Change bitcoin addresses to use testnet prefixes.") gflags.DEFINE_string('rootkey', None, u"BIP-32 root derivation key.") gflags.RegisterValidator('rootkey', lambda rootkey: rootkey is not None and Wallet.from_wallet_key(rootkey).is_private, message=u"Must provide private root derivation key.") gflags.MarkFlagAsRequired('rootkey') gflags.DEFINE_boolean('debug', False, u"Print extra debugging information to stderr") gflags.DEFINE_string('foundation_database', u"sqlite:///foundation.sqlite", u"Connection string for Freicoin Foundation database") gflags.DEFINE_string('fee', u"0.0001", u"Minimum relay fee, per kB") def _validate_fee(fee): try: mpd(fee); return True except:
def PrivKeyFromSecretStringAndSubkeyPath(secretString, subkeyPath): return Wallet.from_master_secret(secretString).subkey_for_path(subkeyPath).bitcoin_address()
#!/usr/bin/python ## CONFIG from config import * logfilename = config['logFilename'] pubKey = config['siteHDPubKey'] orgName = config['orgName'] DEBUG = False ## IMPORTS from pycoin.wallet import Wallet pubWallet = Wallet.from_wallet_key(pubKey) from flask import Flask from flask import request, render_template app = Flask(__name__) import logging log_handler = logging.FileHandler(logfilename) log_handler.setLevel(logging.WARNING) app.logger.addHandler(log_handler) from Crypto.Hash import SHA256 import time # DEBUG STUFF FOR PAYMENTS """ ## Payment stuff, should only record public key
def donationsSubKey(): return Wallet.from_wallet_key(settings.DONATIONS_WALLET_KEY)