def test_mismatch_public_private(self):
     w = Wallet.new_random_wallet()
     self.assertRaises(
         KeyMismatchError, Wallet,
         chain_code=b'0' * 64,
         private_key=self.master_key.private_key,
         public_key=w.public_key)
示例#2
0
    def CreateWallet(self, WavesAddress):

        newWallet = Wallet.new_random_wallet()
        # private_key_hex = newWallet.get_private_key_hex()
        # public_key_hex = newWallet.get_public_key_hex()
        serializedWallet = newWallet.serialize()
        newAddress = newWallet.to_address()

        BTCWallet = create_wallet_from_address(wallet_name=WavesAddress,
                                               address=newAddress,
                                               api_key=self.APIKEY)
        #TODO SAVE WAVESAddress , serializeWlt in DB
        print(BTCWallet)
        con = lite.connect('test.db')
        with con:
            cur = con.cursor()
            cur.execute(
                "CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)"
            )
            cur.execute(
                """INSERT INTO addresses VALUES(?,?,?)""",
                (WavesAddress, serializedWallet, BTCWallet['addresses'][0]))
            con.commit()
            # con.close()

        return {'addresses': BTCWallet['addresses'][0]}
示例#3
0
    def generate(cls, extra_entropy=None, testnet=False):
        network = BitcoinMainNet if not testnet else BitcoinTestNet
        wallet = Wallet.new_random_wallet(extra_entropy, network=network)
        child_account = wallet.get_child(0, is_prime=True)

        return cls(
            pub_key=child_account.serialize_b58(private=False),
            priv_key=child_account.serialize_b58(private=True),
            network=network,
        )
示例#4
0
 def __init__(self, private_keychain=None):
     if private_keychain:
         if isinstance(private_keychain, HDWallet):
             self.hdkeychain = private_keychain
         elif isinstance(private_keychain, (str, unicode)):
             self.hdkeychain = HDWallet.deserialize(private_keychain)
         else:
             raise ValueError('private keychain must be a string')
     else:
         self.hdkeychain = HDWallet.new_random_wallet()
 def __init__(self, private_keychain=None):
     if private_keychain:
         if isinstance(private_keychain, HDWallet):
             self.hdkeychain = private_keychain
         elif isinstance(private_keychain, (str, unicode)):
             self.hdkeychain = HDWallet.deserialize(private_keychain)
         else:
             raise ValueError('private keychain must be a string')
     else:
         self.hdkeychain = HDWallet.new_random_wallet()
示例#6
0
def cli():

    parser = argparse.ArgumentParser(
            description='''Simple BIP32 HD cryptocurrecy command line wallet, with several unique features. ''' + ' '.join([x[1] for x in EXPLAINER_COPY]))
    parser.add_argument('-w', '--wallet',
            dest='wallet',
            default='',
            help='Master private or public key (starts with xprv and xpub for BTC). Can also be UNIX piped in (-w/--w not needed).',
            )
    parser.add_argument("-v", "--verbose",
            dest='verbose',
            default=False,
            action='store_true',
            help="Show detailed logging info",
            )
    parser.add_argument('-b', '--bc-api-key',
            dest='bc_api_key',
            # For all bcwallet users:
            default='9c339f92713518492a4504c273d1d9f9',
            help='BlockCypher API Key to use. If not supplied the default will be used.',
            )
    parser.add_argument('-u', '--units',
            dest='units',
            default='bit',
            choices=UNIT_CHOICES,
            help='Units to represent the currency in user display.',
            )
    parser.add_argument('--version',
            dest='version',
            default=False,
            action='store_true',
            help="Show version and quit",
            )
    args = parser.parse_args()

    if args.verbose:
        global VERBOSE_MODE
        VERBOSE_MODE = True
    verbose_print('args: %s' % args)

    global UNIT_CHOICE
    UNIT_CHOICE = args.units

    if args.version:
        import pkg_resources
        puts(colored.green(str(pkg_resources.get_distribution("bcwallet"))))
        sys.exit()

    if sys.stdin.isatty():
        wallet = args.wallet
        verbose_print('Wallet imported from args')
    else:
        wallet = sys.stdin.readline().strip()
        sys.stdin = open('/dev/tty')
        verbose_print('Wallet imported from pipe')
    verbose_print('wallet %s' % wallet)

    if args.bc_api_key:
        global BLOCKCYPHER_API_KEY
        BLOCKCYPHER_API_KEY = args.bc_api_key
        verbose_print('API Key: %s' % BLOCKCYPHER_API_KEY)
        # Crude check
        if set(BLOCKCYPHER_API_KEY) - set('0123456789abcdef'):
            puts(colored.red('Invalid API Key: %s' % BLOCKCYPHER_API_KEY))
            sys.exit()

    # Check if blockcypher is up (basically if the user's machine is online)
    global USER_ONLINE
    if is_connected_to_blockcypher():
        USER_ONLINE = True

    puts("\nWelcome to bcwallet!")

    puts("\nHere's what makes bcwallet unique:")
    with indent(2):
        for bullet_point, description in EXPLAINER_COPY:
            puts('-%s: %s' % (bullet_point, description))
    puts()

    if wallet:
        network = guess_network_from_mkey(wallet)
        if network:
            # check if valid mkey
            try:
                wallet_obj = Wallet.deserialize(wallet, network=network)
                mpub = wallet_obj.serialize_b58(private=False)
                if wallet_obj.private_key is None:
                    # input was mpub
                    if mpub != wallet:
                        # safety check
                        puts(colored.red("Invalid entry: %s" % wallet))
            except IndexError:
                puts(colored.red("Invalid entry: %s" % wallet))

            # Run the program:
            return wallet_home(wallet_obj)

        else:
            puts(colored.red("Invalid wallet entry: %s" % wallet))

    else:
        puts("You've opened your HD wallet without specifying a master public or master private key, which you can do like this:\n")
        print_bcwallet_basic_priv_opening(priv_to_display='xpriv123...')

        puts("Let's generate a new master private key (locally) for you to use.\n")
        puts('Which currency do you want to create a wallet for?')
        coin_symbol = coin_symbol_chooser(user_prompt=DEFAULT_PROMPT)
        verbose_print(coin_symbol)

        if not coin_symbol:
            puts('Quitting without generating a new wallet!')
            sys.exit()

        network = COIN_SYMBOL_TO_BMERCHANT_NETWORK[coin_symbol]

        puts("\nLet's add some extra entropy in case you're on a fresh boot of a virtual machine, or your random number generator has been compromised by an unnamed three letter agency.")
        puts("Please bang on the keyboard for as long as you like and then hit enter.")
        puts("There's no reason to record this value, it cannot be used to recover your keys.")
        extra_entropy = get_user_entropy(user_prompt='฿ (optional)')

        verbose_print(extra_entropy)
        # worst-case assumption (attacker knows keyspace and length)
        entropy_space = len(extra_entropy) ** len(set(extra_entropy))
        bits_entropy = len(bin(entropy_space)) - 2
        verbose_print('bits of extra_entropy: %s' % bits_entropy)

        user_wallet_obj = Wallet.new_random_wallet(network=network,
                user_entropy=extra_entropy)
        mpriv = user_wallet_obj.serialize_b58(private=True)
        mpub = user_wallet_obj.serialize_b58(private=False)

        puts(colored.green('\nYour master PRIVATE key is: %s (guard this CAREFULLY as it can be used to steal your funds)' % mpriv))
        puts(colored.green('Your master PUBLIC key is: %s\n' % mpub))
        puts('bcwallet will now quit. Open your new wallet anytime like this:\n')
        print_bcwallet_basic_priv_opening(priv_to_display=mpriv)
        puts(BCWALLET_PRIVPIPE_EXPLANATION)
        print_bcwallet_piped_priv_opening(priv_to_display=mpriv)
        sys.exit()
示例#7
0
def cli():

    parser = argparse.ArgumentParser(
            description='''Simple BIP32 HD cryptocurrecy command line wallet, with several unique features. ''' + ' '.join([x[1] for x in EXPLAINER_COPY]))
    parser.add_argument('-w', '--wallet',
            dest='wallet',
            default='',
            help='Master private or public key (starts with xprv and xpub for BTC). Can also be UNIX piped in (-w/--w not needed).',
            )
    parser.add_argument("-v", "--verbose",
            dest='verbose',
            default=False,
            action='store_true',
            help="Show detailed logging info",
            )
    parser.add_argument('-b', '--bc-api-key',
            dest='bc_api_key',
            # For all bcwallet users:
            default='9c339f92713518492a4504c273d1d9f9',
            help='BlockCypher API Key to use. If not supplied the default will be used.',
            )
    parser.add_argument('-u', '--units',
            dest='units',
            default='bit',
            choices=UNIT_CHOICES,
            help='Units to represent the currency in user display.',
            )
    parser.add_argument('--version',
            dest='version',
            default=False,
            action='store_true',
            help="Show version and quit",
            )
    args = parser.parse_args()

    if args.verbose:
        global VERBOSE_MODE
        VERBOSE_MODE = True
    verbose_print('args: %s' % args)

    global UNIT_CHOICE
    UNIT_CHOICE = args.units

    if args.version:
        import pkg_resources
        puts(colored.green(str(pkg_resources.get_distribution("bcwallet"))))
        puts()
        sys.exit()

    if sys.stdin.isatty():
        wallet = args.wallet
        verbose_print('Wallet imported from args')
    else:
        wallet = sys.stdin.readline().strip()
        sys.stdin = open('/dev/tty')
        verbose_print('Wallet imported from pipe')
    verbose_print('wallet %s' % wallet)

    if args.bc_api_key:
        global BLOCKCYPHER_API_KEY
        BLOCKCYPHER_API_KEY = args.bc_api_key
        verbose_print('API Key: %s' % BLOCKCYPHER_API_KEY)
        # Crude check
        if set(BLOCKCYPHER_API_KEY) - set('0123456789abcdef'):
            puts(colored.red('Invalid API Key: %s\n' % BLOCKCYPHER_API_KEY))
            sys.exit()

    # Check if blockcypher is up (basically if the user's machine is online)
    global USER_ONLINE
    if is_connected_to_blockcypher():
        USER_ONLINE = True

    puts("\nWelcome to bcwallet!")

    puts("\nHere's what makes bcwallet unique:")
    with indent(2):
        for bullet_point, description in EXPLAINER_COPY:
            puts('-%s: %s' % (bullet_point, description))
    puts()

    if wallet:
        network = guess_network_from_mkey(wallet)
        if network:
            # check if valid mkey
            try:
                wallet_obj = Wallet.deserialize(wallet, network=network)
                mpub = wallet_obj.serialize_b58(private=False)
                if wallet_obj.private_key is None:
                    # input was mpub
                    if mpub != wallet:
                        # safety check
                        puts(colored.red("Invalid entry: %s" % wallet))
            except IndexError:
                puts(colored.red("Invalid entry: %s" % wallet))

            # Run the program:
            return wallet_home(wallet_obj)

        else:
            puts(colored.red("Invalid wallet entry: %s" % wallet))

    else:
        puts("You've opened your HD wallet without specifying a master public or master private key, which you can do like this:\n")
        print_bcwallet_basic_priv_opening(priv_to_display='xpriv123...')

        puts("Let's generate a new master private key (locally) for you to use.\n")
        puts('Which currency do you want to create a wallet for?')
        coin_symbol = coin_symbol_chooser(user_prompt=DEFAULT_PROMPT)
        verbose_print(coin_symbol)

        if not coin_symbol:
            puts('\nQuitting without generating a new wallet!\n')
            sys.exit()

        network = COIN_SYMBOL_TO_BMERCHANT_NETWORK[coin_symbol]

        puts("\nLet's add some extra entropy in case you're on a fresh boot of a virtual machine, or your random number generator has been compromised by an unnamed three letter agency.")
        puts("Please bang on the keyboard for as long as you like and then hit enter.")
        puts("There's no reason to record this value, it cannot be used to recover your keys.")
        extra_entropy = get_user_entropy(user_prompt='฿ (optional)')

        verbose_print(extra_entropy)
        # worst-case assumption (attacker knows keyspace and length)
        entropy_space = len(extra_entropy) ** len(set(extra_entropy))
        bits_entropy = len(bin(entropy_space)) - 2
        verbose_print('bits of extra_entropy: %s' % bits_entropy)

        user_wallet_obj = Wallet.new_random_wallet(network=network,
                user_entropy=extra_entropy)
        mpriv = user_wallet_obj.serialize_b58(private=True)
        mpub = user_wallet_obj.serialize_b58(private=False)

        puts(colored.green('\nYour master PRIVATE key is: %s (guard this CAREFULLY as it can be used to steal your funds)' % mpriv))
        puts(colored.green('Your master PUBLIC key is: %s\n' % mpub))
        puts('bcwallet will now quit. Open your new wallet anytime like this:\n')
        print_bcwallet_basic_priv_opening(priv_to_display=mpriv)
        puts(BCWALLET_PRIVPIPE_EXPLANATION)
        print_bcwallet_piped_priv_opening(priv_to_display=mpriv)
        puts(BCWALLET_PRIVPIPE_CAT_EXPLANATION)
        print_bcwallet_piped_priv_cat_opening()
        puts(BCWALLET_PIPE_ENCRYPTION_EXPLANATION)
        print_keys_not_saved()
        sys.exit()
 def setUpClass(cls):
     cls.wallet = Wallet.new_random_wallet(network=cls.network)
 def setUp(self):
     self.w = Wallet.new_random_wallet()
     self.pub_derived_private_child = self.w.get_child(100)
     self.wpub = self.w.public_copy()
     self.assertTrue(self.wpub.private_key is None)
示例#10
0
 def setUp(self):
     self.w = Wallet.new_random_wallet()
示例#11
0
 def test_random_wallet(self):
     w = Wallet.new_random_wallet()
     self.assertTrue(Wallet.deserialize(w.serialize()), w)
     self.assertEqual(w.depth, 0)
     self.assertEqual(w.parent_fingerprint, b'0x' + long_to_hex(0, 8))
     self.assertEqual(w.child_number, 0)
示例#12
0
def generate(number_of_users=None,
             number_of_accounts=None,
             key_threshold=None,
             extra_entropy=None):
    _print(term.clear)

    if number_of_users is None:
        number_of_users = _get_input(
            'Enter number of users participating [1]: ',
            input_type=int,
            default=1)

    if number_of_users > 1 and not key_threshold:
        key_threshold = _get_input('Enter key threshold [2]: ',
                                   input_type=int,
                                   default=2)

    if number_of_accounts is None:
        number_of_accounts = _get_input(
            'Enter number of accounts to be created per user [1]: ',
            input_type=int,
            default=1)

    if not extra_entropy:
        extra_entropy = _get_input('Enter additional entropy [None]: ')

    _validate_generate_values(number_of_users, number_of_accounts,
                              key_threshold, extra_entropy)
    _print(
        'The system will now attempt to generate a master key and split it amongst the users\n'
        'This process may take awhile...')

    master_wallet = Wallet.new_random_wallet(extra_entropy)
    serialized_wallet = master_wallet.serialize_b58()

    if number_of_users > 1:
        shares = BitcoinToB58SecretSharer.split_secret(
            serialized_wallet.encode(), key_threshold, number_of_users)
    else:
        shares = None

    for user_index in range(number_of_users):
        _print(('The following screen is meant for user {index} (of {total})\n'
                'Do not press continue if you are not user {index}').format(
                    index=user_index + 1, total=number_of_users),
               formatters=[term.clear, term.red])

        _get_input('Press enter to continue when ready')
        _print(term.clear)

        if number_of_users > 1:
            data = {
                'child':
                '{index} of {total}'.format(index=user_index + 1,
                                            total=number_of_users),
                'master_shard':
                '{}-{}'.format(key_threshold, shares[user_index]),
            }
        else:
            data = {}
        _generateKeys(master_wallet,
                      user_index,
                      number_of_accounts,
                      extra_data=data)

    _print('All done')
示例#13
0
	def CreateWallet(self,WavesAddress):

		con = lite.connect('test.db')
		with con:
			cur = con.cursor()
			cur.execute("""SELECT id FROM addressid WHERE WavesAddress=:adr""",  {"adr": WavesAddress})
			row = cur.fetchone()
			if len(row)>0 :
				BTCWallet = get_wallet_addresses(wallet_name='Noay'+ str(row[0]), api_key=self.APIKEY, coin_symbol=self.coin_symbol)
				cur.execute("""SELECT * FROM addresses WHERE WavesAddress=:adr""",  {"adr": WavesAddress})
				row = cur.fetchone()
				wallet = Wallet.deserialize(row[1] ,  network=BitcoinTestNet)
				ModuleHandler.encode(wallet.get_public_key_hex())
				con.commit()
				return {  'addresses'  : BTCWallet['addresses'][0] 
				, 'public_key' : ModuleHandler.encode( wallet.get_public_key_hex() )  }
			con.commit()

		newWallet = Wallet.new_random_wallet(network=BitcoinTestNet)
		# private_key_hex = newWallet.get_private_key_hex()
		# public_key_hex = newWallet.get_public_key_hex()
		serializedWallet = newWallet.serialize()
		newAddress = newWallet.to_address()

		# print('newAddress : ',newAddress)

		con = lite.connect('test.db')
		with con:
			cur = con.cursor()
			cur.execute("CREATE TABLE IF NOT EXISTS addressid(id INTEGER PRIMARY KEY AUTOINCREMENT, WavesAddress TEXT  NOT NULL )")
			cur.execute("""INSERT INTO addressid (WavesAddress) VALUES(?)""",(WavesAddress,))
			cur.execute("""SELECT id FROM addressid WHERE WavesAddress=:adr""",  {"adr": WavesAddress})
			con.commit()
			row = cur.fetchone()

		# print("row[0] : ",row[0])
		#TODO handle {'error': 'Error: wallet exists'}

		BTCWallet = get_wallet_addresses(wallet_name='Noay'+ str(row[0]), api_key=self.APIKEY, coin_symbol=self.coin_symbol)
		try:
			s = BTCWallet['error']
			print('BTCWallet' , 0)
			BTCWallet = create_wallet_from_address(wallet_name= 'Noay'+ str(row[0]), address=newAddress, api_key=self.APIKEY , coin_symbol=self.coin_symbol)
		
		#TODO SAVE WAVESAddress , serializeWlt in DB
		
		except Exception as e:

			con = lite.connect('test.db')
			print('BTCWallet' , 1)
			with con:
				cur = con.cursor()
				cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT , Inventory REAL)")
				cur.execute("""INSERT INTO addresses VALUES(?,?,?,0)""",(WavesAddress,serializedWallet,BTCWallet['addresses'][0]))
				con.commit()
				# con.close()
		# print('BTCWallet' , BTCWallet)



		return {  'addresses'  : BTCWallet['addresses'][0] 
				, 'public_key' : ModuleHandler.encode( newWallet.get_public_key_hex() )  } # public key btc