def init_wallet(self, identifier, passphrase): netcode = "XTN" if self.testnet else "BTC" data = self.get_wallet(identifier) primary_seed = Mnemonic.to_seed(data['primary_mnemonic'], passphrase) primary_private_key = BIP32Node.from_master_secret(primary_seed, netcode=netcode) backup_public_key = BIP32Node.from_hwif(data['backup_public_key'][0]) checksum = self.create_checksum(primary_private_key) if checksum != data['checksum']: raise Exception("Checksum [%s] does not match expected checksum [%s], most likely due to incorrect password" % (checksum, data['checksum'])) blocktrail_public_keys = data['blocktrail_public_keys'] key_index = data['key_index'] return Wallet( client=self, identifier=identifier, primary_mnemonic=data['primary_mnemonic'], primary_private_key=primary_private_key, backup_public_key=backup_public_key, blocktrail_public_keys=blocktrail_public_keys, key_index=key_index, testnet=self.testnet )
def controller_recover_key(recovery_phrase): #function to recover a public and private key pair from a mnemonic phrase mnemonic_base = Mnemonic(language='english') seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey
def master_key_from_mnemonic(mnemonic, passphrase=''): """ 从助记符生成主密钥。 参数: mnemonic (str): 表示从中生成主密钥的种子的助记词。 passphrase (str): 密码如果使用的话。 返回值: HDPrivateKey: 主私钥。 """ return HDPrivateKey.master_key_from_seed( Mnemonic.to_seed(mnemonic, passphrase))
def mnemonic_to_seed(mnemonic, pass_phrase=''): """Convert mnemonic (phrase) to seed :param mnemonic: A phrase :type mnemonic: str :param pass_phrase: A password :type pass_phrase: str :returns: seed """ mnemo = Mnemonic("english") seed = mnemo.to_seed(mnemonic, pass_phrase) return seed
def master_key_from_mnemonic(mnemonic, passphrase=''): """ Generates a master key from a mnemonic. Args: mnemonic (str): The mnemonic sentence representing the seed from which to generate the master key. passphrase (str): Password if one was used. Returns: HDPrivateKey: the master private key. """ return HDPrivateKey.master_key_from_seed( Mnemonic.to_seed(mnemonic, passphrase))
def master_key_from_entropy(passphrase='', language='english', strength=128): if strength % 32 != 0: raise ValueError("strength must be a multiple of 32") if strength < 128 or strength > 256: raise ValueError("strength should be >= 128 and <= 256") entropy = CobraHDWallet.generate_entropy() mnemonic = Mnemonic(language=language)\ .to_mnemonic(entropy) return CobraHDWallet.master_key_from_seed( Mnemonic.to_seed(mnemonic, passphrase)), mnemonic
def controller_keygen(): #function to generate a random mnemonic recovery phrase #and in turn a private a public keys decode_hex = codecs.getdecoder("hex_codec") entropy_hex = bc.random_key() entropy_bytes = decode_hex(entropy_hex)[0] mnemonic_base = Mnemonic(language='english') recovery_phrase = mnemonic_base.to_mnemonic(entropy_bytes) seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey, recovery_phrase
def mnemonic_to_master(mnemonic, passphrase, netcode='BTC', check=True): if check: if not Mnemonic('english').check(mnemonic): raise RuntimeError( 'mnemonic is non-standard, please check spelling') seed = Mnemonic.to_seed(mnemonic, passphrase=passphrase) if netcode == 'BTC': master = btc.network.keys.bip32_seed(seed) elif netcode == 'XTN': master = xtn.network.keys.bip32_seed(seed) else: raise RuntimeError("unknown netcode") return seed, master
def create_new_wallet(self, identifier, passphrase, key_index=0): netcode = "XTN" if self.testnet else "BTC" primary_mnemonic = Mnemonic(language='english').generate(strength=512) primary_seed = Mnemonic.to_seed(primary_mnemonic, passphrase) primary_private_key = BIP32Node.from_master_secret(primary_seed, netcode=netcode) primary_public_key = primary_private_key.subkey_for_path("%d'.pub" % key_index) backup_mnemonic = Mnemonic(language='english').generate(strength=512) backup_seed = Mnemonic.to_seed(backup_mnemonic, "") backup_public_key = BIP32Node.from_master_secret(backup_seed, netcode=netcode).public_copy() checksum = self.create_checksum(primary_private_key) result = self._create_new_wallet( identifier=identifier, primary_public_key=(primary_public_key.as_text(), "M/%d'" % key_index), backup_public_key=(backup_public_key.as_text(), "M"), primary_mnemonic=primary_mnemonic, checksum=checksum, key_index=key_index ) blocktrail_public_keys = result['blocktrail_public_keys'] key_index = result['key_index'] return Wallet( client=self, identifier=identifier, primary_mnemonic=primary_mnemonic, primary_private_key=primary_private_key, backup_public_key=backup_public_key, blocktrail_public_keys=blocktrail_public_keys, key_index=key_index, testnet=self.testnet ), primary_mnemonic, backup_mnemonic, blocktrail_public_keys
def create(cls, mnemonic=None): """ Create Minter wallet @param mnemonic|string: Mnemonic phrase @return: dict """ # Create mnemonic phrase if None if not mnemonic: _mnemonic = Mnemonic(language='english') mnemonic = _mnemonic.generate(cls.BIP44_ENTROPY_BITS) if len(mnemonic.split(' ')) != 12: raise Exception('Mnemonic phrase should have 12 words.') # Mnemonic to seed (bytes) seed = Mnemonic.to_seed(mnemonic, '') # Generate master key from master seed I = hmac.new(cls.MASTER_SEED, seed, hashlib.sha512).hexdigest() IL = I[:64] IR = I[64:] master_key = HDPrivateKey(key=int.from_bytes(binascii.unhexlify(IL), 'big'), chain_code=binascii.unhexlify(IR), index=0, depth=0) # Get child keys from master key by path keys = HDKey.from_path(master_key, cls.BIP44_SEED_ADDRESS_PATH) # Get private key private_key = binascii.hexlify(bytes(keys[-1]._key)) # Get public key public_key = cls.get_public_from_private(private_key) # Get address address = cls.get_address_from_public_key(public_key) return { 'address': address, 'private_key': private_key.decode(), 'mnemonic': mnemonic, 'seed': binascii.hexlify(seed).decode() }
def create(cls, mnemonic=None): """ Create Minter wallet Args: mnemonic (str): Mnemonic phrase Returns: dict """ # Create mnemonic phrase if None if not mnemonic: _mnemonic = Mnemonic(language='english') mnemonic = _mnemonic.generate(cls.entropy_bits) if len(mnemonic.split(' ')) != 12: raise Exception('Mnemonic phrase should have 12 words.') # Mnemonic to seed (bytes) seed = Mnemonic.to_seed(mnemonic, '') # Generate master key (key, hmac_key) from master seed _I = hmac.new(cls.master_seed, seed, hashlib.sha512).hexdigest() master_key = (int(_I[:64], 16), bytes.fromhex(_I[64:])) # Get child keys from master key by path keys = cls.from_path(root_key=master_key, path=cls.seed_address_path) # Get private key private_key = format(keys[-1][0], '0x') # Get public key from private public_key = cls.get_public_from_private(private_key) # Get address from public key address = cls.get_address_from_public_key(public_key) return { 'address': address, 'private_key': private_key, 'mnemonic': mnemonic, 'seed': seed.hex() }
def master_key_from_entropy(passphrase='', strength=128): """ Generates a master key from system entropy. Args: strength (int): Amount of entropy desired. This should be a multiple of 32 between 128 and 256. passphrase (str): An optional passphrase for the generated mnemonic string. Returns: HDPrivateKey, str: a tuple consisting of the master private key and a mnemonic string from which the seed can be recovered. """ if strength % 32 != 0: raise ValueError("strength must be a multiple of 32") if strength < 128 or strength > 256: raise ValueError("strength should be >= 128 and <= 256") entropy = rand_bytes(strength // 8) m = Mnemonic(language='english') n = m.to_mnemonic(entropy) return HDPrivateKey.master_key_from_seed( Mnemonic.to_seed(n, passphrase)), n
def mnemonic_to_master(mnemonic, passphrase): seed = Mnemonic.to_seed(mnemonic, passphrase=passphrase) master = BIP32Node.from_master_secret(seed) return (seed, master)
def master_key_from_mnemonic(mnemonic, passphrase=''): return CobraHDWallet.master_key_from_seed( Mnemonic.to_seed(mnemonic, passphrase))
def main(): parser = argparse.ArgumentParser( description="Process blinktrade withdrawals requests") parser.add_argument('-c', "--config", action="store", dest="config", help='Configuration file', type=str) arguments = parser.parse_args() candidates = [ os.path.join(site_config_dir('blinktrade'), 'blinktrade_withdrawer.ini'), os.path.expanduser('~/.blinktrade/blinktrade_withdrawer.ini') ] if arguments.config: candidates.append(arguments.config) config = ConfigParser.SafeConfigParser() config.read(candidates) password = getpass.getpass('password: '******'ws': should_connect_on_ssl = False blinktrade_port = 80 db_engine = config.get("database", "sqlalchemy_engine") + ':///' +\ os.path.expanduser(config.get("database", "sqlalchemy_connection_string")) engine = create_engine(db_engine, echo=config.getboolean('database', 'sqlalchmey_verbose')) Base.metadata.create_all(engine) factory = BlinkTradeClientFactory(blinktrade_url.geturl()) factory.db_session = scoped_session(sessionmaker(bind=engine)) factory.verbose = config.getboolean("blinktrade", "verbose") factory.blinktrade_broker_id = config.get("blinktrade", "broker_id") factory.blinktrade_user = config.get("blinktrade", "api_key") factory.blinktrade_password = decrypt( password, unhexlify(config.get("blinktrade", "api_password"))) factory.currencies = json.loads(config.get("blinktrade", "currencies")) factory.methods = json.loads(config.get("blinktrade", "methods")) factory.blocked_accounts = json.loads( config.get("blinktrade", "blocked_accounts")) factory.mandrill_api = mandrill_api if config.has_section('blockchain_info'): from blockchain_info import BlockchainInfoWithdrawalProtocol factory.blockchain_guid = decrypt( password, unhexlify(config.get("blockchain_info", "guid"))) factory.blockchain_main_password = decrypt( password, unhexlify(config.get("blockchain_info", "main_password"))) factory.blockchain_second_password = decrypt( password, unhexlify(config.get("blockchain_info", "second_password"))) factory.blockchain_api_key = config.get("blockchain_info", "api_key") factory.from_address = config.get("blockchain_info", "from_address") factory.note = config.get("blockchain_info", "note") factory.protocol = BlockchainInfoWithdrawalProtocol if config.has_section('blocktrail'): import blocktrail from mnemonic.mnemonic import Mnemonic from pycoin.key.BIP32Node import BIP32Node is_testnet = False if config.get("blocktrail", "testnet") == '1': is_testnet = True client = blocktrail.APIClient( api_key=config.get("blocktrail", "api_key"), api_secret=decrypt( password, unhexlify(config.get("blocktrail", "api_secret"))), network='BTC', testnet=is_testnet) data = client.get_wallet(config.get("blocktrail", "wallet_identifier")) primary_seed = Mnemonic.to_seed( data['primary_mnemonic'], decrypt(password, unhexlify(config.get("blocktrail", "wallet_passphrase")))) primary_private_key = BIP32Node.from_master_secret( primary_seed, netcode='XTN' if client.testnet else 'BTC') backup_public_key = BIP32Node.from_hwif(data['backup_public_key'][0]) checksum = client.create_checksum(primary_private_key) if checksum != data['checksum']: raise Exception("Checksum [%s] does not match expected checksum [%s], " \ "most likely due to incorrect password" % (checksum, data['checksum'])) blocktrail_public_keys = {} for v, k in data['blocktrail_public_keys']: if k in blocktrail_public_keys: blocktrail_public_keys[k].append(v) else: blocktrail_public_keys[k] = [v] key_index = data['key_index'] wallet = blocktrail.wallet.Wallet( client=client, identifier=config.get("blocktrail", "wallet_identifier"), primary_mnemonic=data['primary_mnemonic'], primary_private_key=primary_private_key, backup_public_key=backup_public_key, blocktrail_public_keys=blocktrail_public_keys, key_index=key_index, testnet=client.testnet) from blocktrail_protocol import BlocktrailWithdrawalProtocol factory.blocktrail_wallet = wallet factory.blocktrail_change_address = config.get("blocktrail", "change_address") factory.protocol = BlocktrailWithdrawalProtocol if config.has_section('mailer'): from mailer_protocol import MailerWithdrawalProtocol factory.mandrill_apikey = config.get("mailer", "mandrill_apikey") factory.mandrill_template_name = config.get("mailer", "template_name") factory.mandrill_from_email = config.get("mailer", "from_email") factory.mandrill_from_name = config.get("mailer", "from_name") factory.mandrill_to_email = config.get("mailer", "to_email") factory.mandrill_to_name = config.get("mailer", "to_name") factory.mandrill_website = config.get("mailer", "website") factory.protocol = MailerWithdrawalProtocol if should_connect_on_ssl: reactor.connectSSL(blinktrade_url.netloc, blinktrade_port, factory, ssl.ClientContextFactory()) else: reactor.connectTCP(blinktrade_url.netloc, blinktrade_port, factory) reactor.run()
def main(): parser = argparse.ArgumentParser(description="Process blinktrade withdrawals requests") parser.add_argument('-c', "--config", action="store", dest="config", help='Configuration file', type=str) arguments = parser.parse_args() candidates = [ os.path.join(site_config_dir('blinktrade'), 'blinktrade_withdrawer.ini'), os.path.expanduser('~/.blinktrade/blinktrade_withdrawer.ini')] if arguments.config: candidates.append(arguments.config) config = ConfigParser.SafeConfigParser() config.read( candidates ) password = getpass.getpass('password: '******'ws': should_connect_on_ssl = False blinktrade_port = 80 db_engine = config.get("database", "sqlalchemy_engine") + ':///' +\ os.path.expanduser(config.get("database", "sqlalchemy_connection_string")) engine = create_engine(db_engine, echo=config.getboolean('database', 'sqlalchmey_verbose')) Base.metadata.create_all(engine) factory = BlinkTradeClientFactory(blinktrade_url.geturl()) factory.db_session = scoped_session(sessionmaker(bind=engine)) factory.verbose = config.getboolean("blinktrade", "verbose") factory.blinktrade_broker_id = config.get("blinktrade", "broker_id") factory.blinktrade_user = config.get("blinktrade", "api_key") factory.blinktrade_password = decrypt(password, unhexlify(config.get("blinktrade", "api_password"))) factory.currencies = json.loads(config.get("blinktrade", "currencies")) factory.methods = json.loads(config.get("blinktrade", "methods")) factory.blocked_accounts = json.loads(config.get("blinktrade", "blocked_accounts")) factory.mandrill_api = mandrill_api if config.has_section('blockchain_info'): from blockchain_info import BlockchainInfoWithdrawalProtocol factory.blockchain_guid = decrypt(password, unhexlify(config.get("blockchain_info", "guid"))) factory.blockchain_main_password = decrypt(password, unhexlify(config.get("blockchain_info", "main_password"))) factory.blockchain_second_password = decrypt(password, unhexlify(config.get("blockchain_info", "second_password"))) factory.blockchain_api_key = config.get("blockchain_info", "api_key") factory.from_address = config.get("blockchain_info", "from_address") factory.note = config.get("blockchain_info", "note") factory.protocol = BlockchainInfoWithdrawalProtocol if config.has_section('blocktrail'): import blocktrail from mnemonic.mnemonic import Mnemonic from pycoin.key.BIP32Node import BIP32Node is_testnet = False if config.get("blocktrail", "testnet") == '1': is_testnet = True client = blocktrail.APIClient(api_key=config.get("blocktrail", "api_key"), api_secret=decrypt(password, unhexlify(config.get("blocktrail", "api_secret"))), network='BTC', testnet=is_testnet) data = client.get_wallet(config.get("blocktrail", "wallet_identifier")) primary_seed = Mnemonic.to_seed(data['primary_mnemonic'], decrypt(password, unhexlify(config.get("blocktrail", "wallet_passphrase")))) primary_private_key = BIP32Node.from_master_secret(primary_seed, netcode='XTN' if client.testnet else 'BTC') backup_public_key = BIP32Node.from_hwif(data['backup_public_key'][0]) checksum = client.create_checksum(primary_private_key) if checksum != data['checksum']: raise Exception("Checksum [%s] does not match expected checksum [%s], " \ "most likely due to incorrect password" % (checksum, data['checksum'])) blocktrail_public_keys = {} for v,k in data['blocktrail_public_keys']: if k in blocktrail_public_keys: blocktrail_public_keys[k].append(v) else: blocktrail_public_keys[k] = [v] key_index = data['key_index'] wallet = blocktrail.wallet.Wallet(client=client, identifier= config.get("blocktrail", "wallet_identifier"), primary_mnemonic=data['primary_mnemonic'], primary_private_key=primary_private_key, backup_public_key=backup_public_key, blocktrail_public_keys=blocktrail_public_keys, key_index=key_index, testnet=client.testnet) from blocktrail_protocol import BlocktrailWithdrawalProtocol factory.blocktrail_wallet = wallet factory.blocktrail_change_address = config.get("blocktrail", "change_address") factory.protocol = BlocktrailWithdrawalProtocol if config.has_section('mailer'): from mailer_protocol import MailerWithdrawalProtocol factory.mandrill_apikey = config.get("mailer", "mandrill_apikey") factory.mandrill_template_name = config.get("mailer", "template_name") factory.mandrill_from_email = config.get("mailer", "from_email") factory.mandrill_from_name = config.get("mailer", "from_name") factory.mandrill_to_email = config.get("mailer", "to_email") factory.mandrill_to_name = config.get("mailer", "to_name") factory.mandrill_website = config.get("mailer", "website") factory.protocol = MailerWithdrawalProtocol if should_connect_on_ssl: reactor.connectSSL( blinktrade_url.netloc , blinktrade_port , factory, ssl.ClientContextFactory() ) else: reactor.connectTCP(blinktrade_url.netloc , blinktrade_port , factory ) reactor.run()