def _test_deserialize(self, child, *vector):
     self._test_vector(
         Wallet.deserialize(child.serialize(private=True)),
         *vector)
     self._test_vector(
         Wallet.deserialize(child.serialize(private=False)),
         *vector, include_private=False)
    def test_serialize_public(self):
        pub = self.wallet.serialize(private=False)
        w = Wallet.deserialize(pub, network=self.network)
        self.assertFalse(w.private_key)

        pub = self.wallet.serialize_b58(private=False)
        w = Wallet.deserialize(pub, network=self.network)
        self.assertFalse(w.private_key)
示例#3
0
文件: models.py 项目: hoffmabc/Towan
 def create(self, id):
     if TESTNET :
         child_pubkey = Wallet.deserialize(PUBLIC_KEYCHAIN, BitcoinTestNet).get_child(0).get_child(id)
     else :
         child_pubkey = Wallet.deserialize(PUBLIC_KEYCHAIN, BitcoinMainNet).get_child(0).get_child(id)
     address = child_pubkey.to_address()
     blocktrailAPI.subscribe_address_event(address)
     return self(address=address)
 def _test_deserialize(self, child, *vector):
     self._test(
         Wallet.deserialize(
             child.serialize(private=True), network=self.network),
         *vector)
     self._test(
         Wallet.deserialize(
             child.serialize(private=False), network=self.network),
         *vector, include_private=False)
    def test_serialize_private(self):
        prv = self.wallet.serialize(private=True)
        w = Wallet.deserialize(prv, network=self.network)
        self.assertTrue(w.private_key)
        self.assertEqual(w, self.wallet)

        prv = self.wallet.serialize_b58(private=True)
        w = Wallet.deserialize(prv, network=self.network)
        self.assertTrue(w.private_key)
        self.assertEqual(w, self.wallet)
示例#6
0
文件: models.py 项目: fritexvz/Towan
 def create(self, id):
     if TESTNET:
         child_pubkey = Wallet.deserialize(
             PUBLIC_KEYCHAIN, BitcoinTestNet).get_child(0).get_child(id)
     else:
         child_pubkey = Wallet.deserialize(
             PUBLIC_KEYCHAIN, BitcoinMainNet).get_child(0).get_child(id)
     address = child_pubkey.to_address()
     blocktrailAPI.subscribe_address_event(address)
     return self(address=address)
 async def get_master_wallet(self, private=False):
     bc_config = self.config['blockcypher']
     if bc_config['coin_symbol'] == 'bcy':
         pubkey = bc_config['testnet_wallet_pubkey']
         network = BlockCypherTestNet  # todo BitcoinMainNet
         privkey = bc_config['testnet_private_key']
     else:
         pubkey = bc_config['public_key']
         network = BitcoinMainNet
         privkey = bc_config['private_key']
     if not private:
         master_wallet = Wallet.deserialize(pubkey, network=network)
     else:
         master_wallet = Wallet.deserialize(privkey, network=network)
     return master_wallet
 def test_invalid_network_prefix(self):
     key = self.expected_key
     key = (long_to_hex(BitcoinTestNet.EXT_SECRET_KEY, 8) +
            self.expected_key[8:])
     self.assertRaises(IncompatibleNetworkException,
                       Wallet.deserialize, key, BitcoinMainNet)
     self.assertTrue(Wallet.deserialize(key, BitcoinTestNet))
 def __init__(self, public_keychain):
     if isinstance(public_keychain, HDWallet):
         self.hdkeychain = public_keychain
     elif isinstance(public_keychain, (str, unicode)):
         self.hdkeychain = HDWallet.deserialize(public_keychain)
     else:
         raise ValueError('public keychain must be a string')
示例#10
0
    def priv_key(self):
        if not self.has_private_keys:
            raise ValueError(
                'This Account object does not contain private keys')

        return Wallet.deserialize(self._priv_key,
                                  network=self._network).export_to_wif()
示例#11
0
    def address(self):
        if not self._address:
            wallet = Wallet.deserialize(self._priv_key or self._pub_key,
                                        network=self._network)
            self._address = wallet.to_address()

        return self._address
示例#12
0
 def __init__(self, public_keychain):
     if isinstance(public_keychain, HDWallet):
         self.hdkeychain = public_keychain
     elif isinstance(public_keychain, (str, unicode)):
         self.hdkeychain = HDWallet.deserialize(public_keychain)
     else:
         raise ValueError('public keychain must be a string')
示例#13
0
 def test_public_export(self):
     """Export a node as public."""
     child = self.master_key.get_child(0, as_private=False)
     self.assertEqual(child.private_key, None)
     key = child.serialize(private=False)
     self.assertTrue(
         long_to_hex(BitcoinMainNet.EXT_PUBLIC_KEY, 8) in key)
     self.assertEqual(Wallet.deserialize(key), child)
示例#14
0
 def test_public_child_restore(self):
     pub_child = self.wallet.get_child_for_path("M/0")
     self.assert_public(pub_child)
     loaded = Wallet.deserialize(pub_child.serialize(False))
     self.assertEqual(pub_child, loaded)
     n1 = pub_child.get_child_for_path("m/1")
     n2 = loaded.get_child_for_path("m/1")
     self.assertEqual(n1, n2)
示例#15
0
 def test_bip32(self):
     with open("tests/bip32_test_vector.json", "r") as f:
         vectors = json.loads(f.read())
     for wallet_data in vectors:
         wallet = Wallet.deserialize(wallet_data["private_key"], network=BitcoinMainNet)
         self._test_wallet(wallet, wallet_data)
         for child_data in wallet_data["children"]:
             child = wallet.get_child_for_path(child_data["path"])
             self._test_wallet(child, child_data["child"])
示例#16
0
 def test_bip32(self):
     with open("tests/bip32_test_vector.json", 'r') as f:
         vectors = json.loads(f.read())
     for wallet_data in vectors:
         wallet = Wallet.deserialize(
             wallet_data['private_key'], network=BitcoinMainNet)
         self._test_wallet(wallet, wallet_data)
         for child_data in wallet_data['children']:
             child = wallet.get_child_for_path(child_data['path'])
             self._test_wallet(child, child_data['child'])
 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()
示例#18
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()
示例#19
0
def verify_and_fill_address_paths_from_bip32key(address_paths, master_key,
                                                network):
    '''
    Take address paths and verifies their accuracy client-side.

    Also fills in all the available metadata (WIF, public key, etc)
    '''

    assert network, network

    wallet_obj = Wallet.deserialize(master_key, network=network)

    address_paths_cleaned = []

    for address_path in address_paths:
        path = address_path['path']
        input_address = address_path['address']
        child_wallet = wallet_obj.get_child_for_path(path)

        if child_wallet.to_address() != input_address:
            err_msg = 'Client Side Verification Fail for %s on %s:\n%s != %s' % (
                path,
                master_key,
                child_wallet.to_address(),
                input_address,
            )
            raise Exception(err_msg)

        pubkeyhex = child_wallet.get_public_key_hex(compressed=True)

        server_pubkeyhex = address_path.get('public')
        if server_pubkeyhex and server_pubkeyhex != pubkeyhex:
            err_msg = 'Client Side Verification Fail for %s on %s:\n%s != %s' % (
                path,
                master_key,
                pubkeyhex,
                server_pubkeyhex,
            )
            raise Exception(err_msg)

        address_path_cleaned = {
            'pub_address': input_address,
            'path': path,
            'pubkeyhex': pubkeyhex,
        }

        if child_wallet.private_key:
            privkeyhex = child_wallet.get_private_key_hex()
            address_path_cleaned['wif'] = child_wallet.export_to_wif()
            address_path_cleaned['privkeyhex'] = privkeyhex
        address_paths_cleaned.append(address_path_cleaned)

    return address_paths_cleaned
示例#20
0
    def setUpClass(cls):
        """
        This particular key was found by accident to cause the public
        deserialized wallet to have a bad public key point!

        There was a bug that did not properly handle restoring a key from
        a compressed point that had an odd beta parameter.
        (see PublicKey.from_hex_key)
        """
        cls.wallet = Wallet.deserialize(
            u'xprv9s21ZrQH143K319oTMcEt2n2g51StkEnXq23t52ajHM4zFX7cyPqaHShDod'
            'cHAqorNQuDW82jUhXJLomy5A8kM36y8HntnosgCvc1szPJ6x')
示例#21
0
 def setUpClass(cls):
     cls.expected_key = ensure_bytes(
         "0488ade4"  # BitcoinMainNet version
         "00"  # depth
         "00000000"  # parent fingerprint
         "00000000"  # child_number
         # chain_code
         "873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508"
         "00"  # key identifier
         # private exponent
         "e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")
     cls.master_key = Wallet.deserialize(cls.expected_key)
示例#22
0
def verify_and_fill_address_paths_from_bip32key(address_paths, master_key, network):
    '''
    Take address paths and verifies their accuracy client-side.

    Also fills in all the available metadata (WIF, public key, etc)
    '''

    assert network, network

    wallet_obj = Wallet.deserialize(master_key, network=network)

    address_paths_cleaned = []

    for address_path in address_paths:
        path = address_path['path']
        input_address = address_path['address']
        child_wallet = wallet_obj.get_child_for_path(path)

        if child_wallet.to_address() != input_address:
            err_msg = 'Client Side Verification Fail for %s on %s:\n%s != %s' % (
                    path,
                    master_key,
                    child_wallet.to_address(),
                    input_address,
                    )
            raise Exception(err_msg)

        pubkeyhex = child_wallet.get_public_key_hex(compressed=True)

        server_pubkeyhex = address_path.get('public')
        if server_pubkeyhex and server_pubkeyhex != pubkeyhex:
            err_msg = 'Client Side Verification Fail for %s on %s:\n%s != %s' % (
                    path,
                    master_key,
                    pubkeyhex,
                    server_pubkeyhex,
                    )
            raise Exception(err_msg)

        address_path_cleaned = {
            'pub_address': input_address,
            'path': path,
            'pubkeyhex': pubkeyhex,
            }

        if child_wallet.private_key:
            privkeyhex = child_wallet.get_private_key_hex()
            address_path_cleaned['wif'] = child_wallet.export_to_wif()
            address_path_cleaned['privkeyhex'] = privkeyhex
        address_paths_cleaned.append(address_path_cleaned)

    return address_paths_cleaned
示例#23
0
def do_master_and_child_keys_match(public_keychain, child_public_key, chain_path):
    public_child = Wallet.deserialize(public_keychain)
    chain_step_bytes = 4
    max_bits_per_step = 2**31
    chain_steps = [
        int(chain_path[i:i+chain_step_bytes*2], 16) % max_bits_per_step
        for i in range(0, len(chain_path), chain_step_bytes*2)
    ]
    for step in chain_steps:
        public_child = public_child.get_child(step)
    public_child_hex = public_child.get_public_key_hex(compressed=True)
    if public_child_hex == child_public_key:
        return True
    return False
示例#24
0
def test_file():
    for filename, network in [("tests/bip32_test_vector.json", BitcoinMainNet),
                              ("tests/bip32_blockcypher_test_vector.json",
                               BlockCypherTestNet)]:
        with open(filename, 'r') as f:
            vectors = json.loads(f.read())
        for wallet_data in vectors:
            wallet = Wallet.deserialize(wallet_data['private_key'],
                                        network=network)
            # use yield for nose test generation
            yield _test_wallet, wallet, wallet_data
            for child_data in wallet_data['children']:
                child = wallet.get_child_for_path(child_data['path'])
                yield _test_wallet, child, child_data['child']
示例#25
0
	def SettleTransaction(self,WavesAddress):


		#check transaction WavesAddress and WAVES : attchment BTCaddress and verify assetID 
		# trnc = ModuleHandler.wrapper("/transactions/address/" + WavesAddress + "/limit/1")
		pywaves.setNode(node = pywaves.getNode() , chain = self.CHAIN)
		print("getNode(): ",pywaves.getNode())
		trnc = pywaves.wrapper("/transactions/address/" + WavesAddress + "/limit/1" ,  host = self.TESTNET_NODE )
		print('trnc',trnc)
		BTCaddress = trnc[0][0]['attachment']
		if BTCaddress == '' :
			return {"result" : "there is not any transaction!" }

		
		assetDetail = ModuleHandler.wrapper("/assets/details/" + trnc[0][0]['assetId']  ,  host = self.TESTNET_NODE)
		print('assetDetail :  ',assetDetail)
		decimals = assetDetail['decimals']


		con = lite.connect('test.db')
		with con:
			cur = con.cursor()
			# cur.execute("SELECT MIN(cnt) FROM (SELECT COUNT(*) cnt FROM voting GROUP BY candidate) t;")
			# minimumMigdar = cur.fetchone()
			cur.execute("""SELECT * FROM addresses ORDER BY Inventory DESC """)						#TODO change query for get min count 
			con.commit()
			rows = cur.fetchall()
			cnt = 0
			remind = amount*(10**((-1)*decimals)) #### Decimals Decimals Decimals
			while remind > 0:
				serializedWallet = rows[cnt][1]				#ref to DB structure
				wallet = Wallet.deserialize(serializedWallet , network=BitcoinTestNet)
				inv = rows[cnt][3]

				if inv >= remind :
					
					blockcypher.simple_spend(from_privkey=ModuleHandler.encode( wallet.get_private_key_hex() ) , to_address = BTCaddress , to_satoshis = remind)
					cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """,  ( inv - remind , WavesAddress ))
				

				else :

					blockcypher.simple_spend(from_privkey=ModuleHandler.encode( wallet.get_private_key_hex() ) , to_address = BTCaddress , to_satoshis = inv)
					remind = remind - inv
					cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """,  ( 0 , WavesAddress ))
				con.commit()
			
				
		return res
示例#26
0
def do_master_and_child_keys_match(public_keychain, child_public_key,
                                   chain_path):
    public_child = Wallet.deserialize(public_keychain)
    chain_step_bytes = 4
    max_bits_per_step = 2**31
    chain_steps = [
        int(chain_path[i:i + chain_step_bytes * 2], 16) % max_bits_per_step
        for i in range(0, len(chain_path), chain_step_bytes * 2)
    ]
    for step in chain_steps:
        public_child = public_child.get_child(step)
    public_child_hex = public_child.get_public_key_hex(compressed=True)
    if public_child_hex == child_public_key:
        return True
    return False
示例#27
0
文件: utils.py 项目: c4road/pegaso
def get_payment_adress_for_user(user):

    user_id = user.id

    # assert isinstance(user_id, (int,long))

    wallet = Wallet.deserialize(settings.WALLET_PRIVKEY,
                                network=BlockCypherTestNet)
    wallet_for_user = wallet.get_child(user.id, is_prime=True)

    my_wallet = {
        'address': wallet_for_user.to_address(),
        'priv': get_encripted_priv(wallet_for_user),
        # 'reg_priv': wallet_for_user.serialize_b58(private=True)
        'reg_priv': wallet_for_user.get_private_key_hex().decode('UTF-8')
    }

    return my_wallet
示例#28
0
    def pub_key(self):
        if not self._pub_key:
            wallet = Wallet.deserialize(self._priv_key, network=self._network)
            self._pub_key = wallet.serialize_b58(private=False)

        return self._pub_key
示例#29
0
def recover():
    shards = []

    user_index = _get_input(
        "Enter the index of the user who's key should be regenerated: ",
        input_type=int) - 1
    number_of_accounts = _get_input(
        'Enter number of accounts to be created per user [1]: ',
        input_type=int,
        default=1)
    _print(term.clear)

    key_progress = 0
    finished = False

    while not finished:
        _print(term.clear)
        if key_progress == 0:
            _print(
                'Starting on the next screen, each user will be asked to input their piece of the master key.'
            )
        else:
            _print('The next screen is for the next user.')
        _get_input('Press enter to continue')

        _print(term.clear)
        _print('Attempting to recover keys for user {}'.format(user_index + 1))
        _print('Key progress: {}'.format(key_progress))
        _print()

        piece = decrypt_shard()

        threshold, shard = piece.split('-', 1)
        shards.append(shard)
        threshold = int(threshold)

        if key_progress == 0:
            initial_threshold = threshold
        else:
            if initial_threshold != threshold:
                raise ValueError(
                    'Shard thresholds do not match. An invalid shard has been provided.'
                )

        _print()
        _print('Shard has been accepted', formatters=term.blue)
        _get_input('Press enter to continue')

        key_progress += 1

        if key_progress == threshold:
            finished = True

    _print('The next screen is meant for user {}'.format(user_index + 1),
           formatters=term.clear)
    _get_input('Press enter to continue')

    master_key = BitcoinToB58SecretSharer.recover_secret(shards)
    master_wallet = Wallet.deserialize(master_key)

    user_share = BitcoinToB58SecretSharer.recover_share(shards, user_index + 1)

    data = {
        'child': 'user {}'.format(user_index + 1),
        'master_shard': '{}-{}'.format(threshold, user_share),
    }

    _generateKeys(master_wallet,
                  user_index,
                  number_of_accounts,
                  extra_data=data)
示例#30
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()
示例#31
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)
示例#32
0
 def setUpClass(cls):
     cls.master_key = Wallet.deserialize(
         'Ltpv71G8qDifUiNetGsQje8NP1KYECbgKwSP2kugo4qN9GPfJ1KB8XMXxqBTYsA5'
         'PgwQaFV9u5PhKxosbjcnKKCPpPvaYVSUz24KMctXYig39Te',
         cls.network
     )
示例#33
0
 def setUpClass(cls):
     cls.master_key = Wallet.deserialize(
         'dgpv51eADS3spNJh8qd8KgFeT3V2QZBDSkYUqbaKDwZpDN4jd3uLcR7i6CruVDsb'
         'acyx3NL2puToxM9MQYhZSsD8tBkXeQkm5btsKxpZawwPQND',
         cls.network
     )
示例#34
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
示例#35
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()
示例#36
0
 def create(self, id):
     child_pubkey = Wallet.deserialize(PUBLIC_KEYCHAIN_TESTNET, BitcoinTestNet).get_child(id)
     address = child_pubkey.to_address()
     return self(address=address)
示例#37
0
 def test_deserialize_byte_array(self):
     key = binascii.unhexlify(self.wallet.serialize())
     w = Wallet.deserialize(key, network=self.network)
     self.assertEqual(w, self.wallet)