def test_restore_keystore_from_mnemonic(tmpdir, mocker): # Setup spy = mocker.spy(Mnemonic, 'generate') # Decrypt post-generation keystore = Keystore.generate(INSECURE_DEVELOPMENT_PASSWORD, keystore_dir=tmpdir) keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) mnemonic = Mnemonic(_MNEMONIC_LANGUAGE) words = spy.spy_return secret = bytes(mnemonic.to_entropy(words)) keystore_path = keystore.keystore_path # remove local and disk references, simulating a # lost keystore or forgotten password. del keystore os.unlink(keystore_path) # prove the keystore is lost or missing assert not keystore_path.exists() with pytest.raises(Keystore.NotFound): _keystore = Keystore(keystore_path=keystore_path) # Restore with user-supplied words and a new password keystore = Keystore.restore(words=words, password='******') keystore.unlock(password='******') assert keystore._Keystore__secret == secret
def is_mnemonic(mnemonic: str, language: Optional[str] = None) -> bool: """ Check mnemonic words. :param mnemonic: Mnemonic words. :type mnemonic: str :param language: Mnemonic language, default to None. :type language: str :returns: bool -- Mnemonic valid/invalid. >>> from swap.utils import is_mnemonic >>> is_mnemonic(mnemonic="sceptre capter séquence girafe absolu relatif fleur zoologie muscle sirop saboter parure") True """ if language and language not in ["english", "french", "italian", "japanese", "chinese_simplified", "chinese_traditional", "korean", "spanish"]: raise ValueError("invalid language, use only this options english, french, " "italian, spanish, chinese_simplified, chinese_traditional, japanese or korean languages.") try: mnemonic = unicodedata.normalize("NFKD", mnemonic) if language is None: for _language in ["english", "french", "italian", "chinese_simplified", "chinese_traditional", "japanese", "korean", "spanish"]: valid = False if Mnemonic(language=_language).check(mnemonic=mnemonic) is True: valid = True break return valid else: return Mnemonic(language=language).check(mnemonic=mnemonic) except: return False
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 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 restore(cls, words: str, password: str, keystore_dir: Optional[Path] = None) -> 'Keystore': """Restore a keystore from seed words""" __mnemonic = Mnemonic(_MNEMONIC_LANGUAGE) __secret = bytes(__mnemonic.to_entropy(words)) path = Keystore.__save(secret=__secret, password=password, keystore_dir=keystore_dir) keystore = cls(keystore_path=path) return keystore
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 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 get_mnemonic_language(mnemonic: str) -> str: """ Get mnemonic language. :param mnemonic: Mnemonic words. :type mnemonic: str :returns: str -- Mnemonic language. >>> from swap.utils import get_mnemonic_language >>> get_mnemonic_language(mnemonic="sceptre capter séquence girafe absolu relatif fleur zoologie muscle sirop saboter parure") "french" """ if not is_mnemonic(mnemonic=mnemonic): raise ValueError("Invalid mnemonic words.") language = None mnemonic = unicodedata.normalize("NFKD", mnemonic) for _language in ["english", "french", "italian", "chinese_simplified", "chinese_traditional", "japanese", "korean", "spanish"]: if Mnemonic(language=_language).check(mnemonic=mnemonic) is True: language = _language break return language
def entropy_to_mnemonic(entropy: str, language: str = "english") -> str: """ Get mnemonic from entropy hex string. :param entropy: Entropy hex string. :type entropy: str :param language: Mnemonic language, default to english. :type language: str :returns: str -- Mnemonic words. >>> from swap.utils import entropy_to_mnemonic >>> entropy_to_mnemonic(entropy="ee535b143b0d9d1f87546f9df0d06b1a", language="korean") "학력 외침 주민 스위치 출연 연습 근본 여전히 울음 액수 귀신 마누라" """ if not is_entropy(entropy=entropy): raise ValueError("Invalid entropy hex string.") if language and language not in ["english", "french", "italian", "japanese", "chinese_simplified", "chinese_traditional", "korean", "spanish"]: raise ValueError("Invalid language, use only this options english, french, " "italian, spanish, chinese_simplified, chinese_traditional, japanese or korean languages.") return Mnemonic(language=language).to_mnemonic(unhexlify(entropy))
def generate_mnemonic(language: str = "english", strength: int = 128) -> str: """ Generate mnemonic words. :param language: Mnemonic language, default to english. :type language: str :param strength: Entropy strength, default to 128. :type strength: int :returns: str -- Mnemonic words. >>> from swap.utils import generate_mnemonic >>> generate_mnemonic(language="french") "sceptre capter séquence girafe absolu relatif fleur zoologie muscle sirop saboter parure" """ if language and language not in ["english", "french", "italian", "japanese", "chinese_simplified", "chinese_traditional", "korean", "spanish"]: raise ValueError("invalid language, use only this options english, french, " "italian, spanish, chinese_simplified, chinese_traditional, japanese or korean languages.") if strength not in [128, 160, 192, 224, 256]: raise ValueError( "Strength should be one of the following " "[128, 160, 192, 224, 256], but it is not (%d)." % strength ) return Mnemonic(language=language).generate(strength=strength)
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 test_decrypt_keystore(tmpdir, mocker): # Setup spy = mocker.spy(Mnemonic, 'generate') # Decrypt post-generation keystore = Keystore.generate(INSECURE_DEVELOPMENT_PASSWORD, keystore_dir=tmpdir) keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) mnemonic = Mnemonic(_MNEMONIC_LANGUAGE) words = spy.spy_return secret = bytes(mnemonic.to_entropy(words)) assert keystore._Keystore__secret == secret # Decrypt from keystore file keystore_path = keystore.keystore_path del words del keystore keystore = Keystore(keystore_path=keystore_path) keystore.unlock(INSECURE_DEVELOPMENT_PASSWORD) assert keystore._Keystore__secret == secret
def is_mnemonic(mnemonic: str, language: Optional[str] = None) -> bool: """ Check mnemonic words. :param mnemonic: Mnemonic words. :type mnemonic: str :param language: Mnemonic language, default to None. :type language: str :returns: bool -- True/False. >>> from pybytom.utils import is_mnemonic >>> is_mnemonic("sceptre capter séquence girafe absolu relatif fleur zoologie muscle sirop saboter parure") True """ if language and language not in [ "english", "french", "italian", "japanese", "chinese_simplified", "chinese_traditional", "korean", "spanish" ]: raise ValueError( "Invalid language, choose only the following options 'english', 'french', 'italian', " "'spanish', 'chinese_simplified', 'chinese_traditional', 'japanese or 'korean' languages." ) try: mnemonic = unicodedata.normalize("NFKD", mnemonic) if language is None: for _language in [ "english", "french", "italian", "chinese_simplified", "chinese_traditional", "japanese", "korean", "spanish" ]: valid = False if Mnemonic(language=_language).check( mnemonic=mnemonic) is True: valid = True break return valid else: return Mnemonic(language=language).check(mnemonic=mnemonic) except: return False
def generate( cls, password: str, keystore_dir: Optional[Path] = None, interactive: bool = True, ) -> Union['Keystore', Tuple['Keystore', str]]: """Generate a new nucypher keystore for use with characters""" mnemonic = Mnemonic(_MNEMONIC_LANGUAGE) __words = mnemonic.generate(strength=_ENTROPY_BITS) if interactive: cls._confirm_generate(__words) __secret = bytes(mnemonic.to_entropy(__words)) path = Keystore.__save(secret=__secret, password=password, keystore_dir=keystore_dir) keystore = cls(keystore_path=path) if interactive: return keystore return keystore, __words
def master_key_from_mnemonic(mnemonic, passphrase=''): """ 从助记符生成主密钥。 参数: mnemonic (str): 表示从中生成主密钥的种子的助记词。 passphrase (str): 密码如果使用的话。 返回值: HDPrivateKey: 主私钥。 """ return HDPrivateKey.master_key_from_seed( Mnemonic.to_seed(mnemonic, passphrase))
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_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 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 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_entropy(mnemonic: str, language: Optional[str] = None) -> str: """ Get entropy from mnemonic words. :param mnemonic: Mnemonic words. :type mnemonic: str :param language: Mnemonic language, default to english. :type language: str :returns: str -- Enropy hex string. >>> from swap.utils import mnemonic_to_entropy >>> mnemonic_to_entropy(mnemonic="학력 외침 주민 스위치 출연 연습 근본 여전히 울음 액수 귀신 마누라", language="korean") "ee535b143b0d9d1f87546f9df0d06b1a" """ if not is_mnemonic(mnemonic=mnemonic, language=language): raise ValueError("Invalid mnemonic words.") mnemonic = unicodedata.normalize("NFKD", mnemonic) language = language if language else get_mnemonic_language(mnemonic=mnemonic) return Mnemonic(language=language).to_entropy(mnemonic).hex()
class TonlibTestAsyncCase2(unittest.TestCase): keystore = os.path.join(proj_path, 'tmp') vect = '23454927' * 5 local_password = '******' key_password = '******' mn = Mnemonic("english") mn_phrase = mn.to_mnemonic(unhexlify(vect)).split(' ') t = TonlibClientAsyncio(keystore=keystore) def _create_new_key(self): coro = self.t.create_new_key(local_password=self.local_password, mnemonic=self.mn_phrase) res = coro_result(coro) self.assertIsInstance(res, dict) self.assertEqual(res['@type'], 'key') return res def _delete_key(self, public_key, secret): coro = self.t.delete_key(public_key=public_key, secret=secret) res = coro_result(coro) self.assertIsInstance(res, dict) self.assertEqual(res['@type'], 'ok') def setUp(self): uvloop.install() def test_export_key(self): res_create_new_key = self._create_new_key() coro_export_key = self.t.export_key( public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret'], local_password=self.local_password) res_export_key = coro_result(coro_export_key) self.assertIsInstance(res_export_key, dict) self.assertEqual(res_export_key['@type'], 'exportedKey') self._delete_key(public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret'])
#!/usr/bin/env python3 from shuttle.utils import sha256, double_sha256, \ generate_mnemonic, generate_passphrase from mnemonic.mnemonic import Mnemonic mnemonic = Mnemonic(language="korean") def test_shuttle_utils(): assert sha256("meherett".encode()).hex() == \ "d4f5c55a45c004660b95ec833bb24569eba1559f214e90efa6e8d0b3afa14394" assert double_sha256("meherett".encode()).hex() == \ "2803bf9ed1e5874825350b1b0753a96c00a99236b686bde337404453b11d3288" generated_mnemonic = generate_mnemonic(language="korean") assert mnemonic.check(generated_mnemonic) assert len(generate_passphrase(length=100)) == 100
def generate(data=None): if data is None: data = os.urandom(16) return Mnemonic('english').to_mnemonic(data)
def mnemonic_to_master(mnemonic, passphrase): seed = Mnemonic.to_seed(mnemonic, passphrase=passphrase) master = BIP32Node.from_master_secret(seed) return (seed, master)
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()
def master_key_from_mnemonic(mnemonic, passphrase=''): return CobraHDWallet.master_key_from_seed( Mnemonic.to_seed(mnemonic, passphrase))
def check_master_key_from_mnemonic(mnemonic, language='english'): try: Mnemonic(language=language).check(mnemonic) return True except: return False
class ClientKeyingTestCase(unittest.TestCase): keystore = os.path.join(proj_path, 'tmp') vect = '23454927' * 5 local_password = '******' key_password = '******' mn = Mnemonic("english") mn_phrase = mn.to_mnemonic(unhexlify(vect)).split(' ') t = TonlibClientFutures(keystore=keystore) def _create_new_key(self): ft = self.t.create_new_key(local_password=self.local_password, mnemonic=self.mn_phrase) res = ft.result() self.assertIsInstance(res, dict) self.assertEqual('key', res['@type']) return res def _delete_key(self, public_key, secret): ft = self.t.delete_key(public_key=public_key, secret=secret) res = ft.result() self.assertIsInstance(res, dict) self.assertEqual('ok', res['@type']) def test_create_new_key(self): res_create_new_key = self.t.create_new_key( local_password=self.local_password, mnemonic=self.mn_phrase).result() self.assertIsInstance(res_create_new_key, dict) self.assertEqual('key', res_create_new_key['@type']) self._delete_key(public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret']) def test_export_key(self): res_create_new_key = self._create_new_key() res_export_key = self.t.export_key( public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret'], local_password=self.local_password).result() self.assertIsInstance(res_export_key, dict) self.assertEqual('exportedKey', res_export_key['@type']) self._delete_key(public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret']) def _test_export_pem_key(self): res_create_new_key = self._create_new_key() res_export_pem_key = self.t.export_pem_key( public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret'], local_password=self.local_password, key_password=self.key_password).result() self.assertIsInstance(res_export_pem_key, dict) self.assertEqual('exportedKey', res_export_pem_key['@type']) self._delete_key(public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret']) def test_export_encrypted_key(self): res_create_new_key = self._create_new_key() res_export_encrypted_key = self.t.export_encrypted_key( public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret'], local_password=self.local_password, key_password=self.key_password).result() self.assertIsInstance(res_export_encrypted_key, dict) self.assertEqual('exportedEncryptedKey', res_export_encrypted_key['@type']) self._delete_key(public_key=res_create_new_key['public_key'], secret=res_create_new_key['secret']) def _test_import_key(self): res_import_key = self.t.import_key(local_password=self.local_password, mnemonic_password=self.key_password, mnemonic=self.mn_phrase).result() self.assertIsInstance(res_import_key, dict) self.assertEqual('key', res_import_key['@type']) self._delete_key(public_key=res_import_key['public_key'], secret=res_import_key['secret'])