Esempio n. 1
0
def init_profile(user,
                 is_social=False,
                 metamask_address=None,
                 lang='en',
                 swaps=False):
    m = hashlib.sha256()
    memo_str1 = generate_memo(m)
    # memo_str2 = generate_memo(m)
    # memo_str3 = generate_memo(m)
    memo_str4 = generate_memo(m)
    memo_str5 = generate_memo(m)
    # memo_str6 = generate_memo(m)

    wish_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY, public=True)
    # eosish_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY_EOSISH, public=True)
    # tron_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY_TRON, public=True)
    swaps_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY_SWAPS, public=True)
    protector_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY_PROTECTOR,
                                             public=True)

    btc_address1 = wish_key.ChildKey(user.id).Address()
    # btc_address2 = eosish_key.ChildKey(user.id).Address()
    # btc_address3 = tron_key.ChildKey(user.id).Address()
    btc_address4 = swaps_key.ChildKey(user.id).Address()
    btc_address5 = protector_key.ChildKey(user.id).Address()
    # btc_address6 = swaps_key.ChildKey(user.id).Address()
    eth_address1 = keys.PublicKey(wish_key.ChildKey(
        user.id).K.to_string()).to_checksum_address().lower()
    # eth_address2 = keys.PublicKey(eosish_key.ChildKey(user.id).K.to_string()).to_checksum_address().lower()
    # eth_address3 = keys.PublicKey(tron_key.ChildKey(user.id).K.to_string()).to_checksum_address().lower()
    eth_address4 = keys.PublicKey(swaps_key.ChildKey(
        user.id).K.to_string()).to_checksum_address().lower()
    eth_address5 = keys.PublicKey(
        protector_key.ChildKey(
            user.id).K.to_string()).to_checksum_address().lower()
def init_profile(user, is_social=False, metamask_address=None, lang='en'):
    m = hashlib.sha256()
    memo_str1 = generate_memo(m)
    # memo_str2 = generate_memo(m)
    # memo_str3 = generate_memo(m)
    memo_str4 = generate_memo(m)

    wish_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY, public=True)
    # eosish_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY_EOSISH, public=True)
    # tron_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY_TRON, public=True)
    swaps_key = BIP32Key.fromExtendedKey(ROOT_PUBLIC_KEY_SWAPS, public=True)

    btc_address1 = wish_key.ChildKey(user.id).Address()
    # btc_address2 = eosish_key.ChildKey(user.id).Address()
    # btc_address3 = tron_key.ChildKey(user.id).Address()
    btc_address4 = swaps_key.ChildKey(user.id).Address()
    eth_address1 = keys.PublicKey(wish_key.ChildKey(
        user.id).K.to_string()).to_checksum_address().lower()
    # eth_address2 = keys.PublicKey(eosish_key.ChildKey(user.id).K.to_string()).to_checksum_address().lower()
    # eth_address3 = keys.PublicKey(tron_key.ChildKey(user.id).K.to_string()).to_checksum_address().lower()
    eth_address4 = keys.PublicKey(swaps_key.ChildKey(
        user.id).K.to_string()).to_checksum_address().lower()

    Profile(user=user,
            is_social=is_social,
            metamask_address=metamask_address,
            lang=lang).save()
    create_wish_balance(user, eth_address1, btc_address1, memo_str1)
    # create_eosish_balance(user, eth_address2, btc_address2, memo_str2)
    # create_tron_balance(user, eth_address3, btc_address3, memo_str3)
    create_swaps_balance(user, eth_address4, btc_address4, memo_str4)
    registration_btc_address(btc_address1)
    # registration_btc_address(btc_address2)
    # registration_btc_address(btc_address3)
    registration_btc_address(btc_address4)
    def generate_keys(self):
        eth_btc_root_pub_key = get_root_key()
        eth_btc_root_key = BIP32Key.fromExtendedKey(eth_btc_root_pub_key,
                                                    public=True)
        eth_btc_child_key = eth_btc_root_key.ChildKey(self.user.id)
        btc_address = eth_btc_child_key.Address()
        registration_btc_address(btc_address)
        eth_address = keys.PublicKey(
            eth_btc_child_key.K.to_string()).to_checksum_address().lower()

        duc_root_key = DucatusWallet.deserialize(
            ROOT_KEYS['ducatus']['public'])
        duc_address = duc_root_key.get_child(self.user.id,
                                             is_prime=False).to_address()

        ducx_root_pub_key = ROOT_KEYS['ducatusx']['public']
        ducx_root_key = BIP32Key.fromExtendedKey(ducx_root_pub_key,
                                                 public=True)
        ducx_child_key = ducx_root_key.ChildKey(self.user.id)
        ducx_address = keys.PublicKey(
            ducx_child_key.K.to_string()).to_checksum_address().lower()

        self.btc_address = btc_address
        self.eth_address = eth_address
        self.duc_address = duc_address
        self.ducx_address = ducx_address

        self.save()
Esempio n. 4
0
def subkey(index):
    qtctl_env = os.environ.copy()
    qtctl_env["QTCTL_KEY"] = "xprv9v3URixxtyRbDyys2zmY7xxtt2NvjpsdR3DHu7djw9AckBowqBFuSDamhVpn127WDfcbsGbSwqLayFueXEPrpyPTqMNbJ6XCnS7obNyDsyn"
    qtctl_env["QTCTL_ADDRESSVERSION"] = "0"

    ex_key = BIP32Key.fromExtendedKey(qtctl_env["QTCTL_KEY"])
    key = ex_key.ChildKey(int(index))
    child_key = BIP32Key.fromExtendedKey(key.ExtendedKey())
    private_key = child_key.PrivateKey().hex()
    public_key = child_key.PublicKey().hex()
    address = str(P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(public_key)))
    
    return {'public_key': public_key, 'index': index, "private_key": private_key, 'address': address}
Esempio n. 5
0
 def __init__(self, xpub):
     self.addresses = []
     self.transactions = []
     self.gap = 10
     self.acc_node = BIP32Key.fromExtendedKey(xpub)
     self.ext_node = self.acc_node.ChildKey(0)
     self.int_node = self.acc_node.ChildKey(1)
Esempio n. 6
0
    def generate(cls, xprv=None, prv=None, seed=None, child=None, username=None):
        mnemonic = Mnemonic('english')
        # generate 12 word mnemonic seed
        if not seed and not xprv and not prv:
            seed = mnemonic.generate(256)
        private_key = None
        if seed:
            # create bitcoin wallet
            entropy = mnemonic.to_entropy(seed)
            key = BIP32Key.fromEntropy(entropy)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
        else:
            raise Exception('No Seed')
        if prv:
            private_key = PrivateKey.from_hex(bytes.fromhex(prv)).to_hex()
            extended_key = ''

        if xprv:
            key = BIP32Key.fromExtendedKey(xprv)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
        
        if xprv and child:
            for x in child:
                key = key.ChildKey(int(x))
                private_key = key.PrivateKey().hex()

        if not private_key:
            raise Exception('No key')

        return cls({
            "seed": seed or '',
            "xprv": extended_key or '',
            "private_key": private_key,
            "wif": cls.generate_wif(private_key),
            "public_key": PublicKey.from_point(key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex(),
            "address": str(key.Address()),
            "serve_host": "0.0.0.0",
            "serve_port": 8000,
            "use_pnp": True,
            "ssl": False,
            "origin": '',
            "polling": 0,
            "post_peer": False,
            # "public_ip": "",  # TODO
            "peer_host": "",
            "peer_port": 8000,
            "web_server_host": "0.0.0.0",
            "web_server_port": 5000,
            "peer": "http://localhost:8000",
            "callbackurl": "http://0.0.0.0:5000/create-relationship",
            "fcm_key": "",
            "database": "yadacoin",
            "site_database": "yadacoinsite",
            "mongodb_host": "localhost",
            "mixpanel": "",
            "username": username or '',
            "network": "mainnet"
        })
Esempio n. 7
0
 def __init__(self, xpub):
     self.addresses = []
     self.transactions = []
     self.gap = 10
     self.acc_node = BIP32Key.fromExtendedKey(xpub)
     self.ext_node = self.acc_node.ChildKey(0)
     self.int_node = self.acc_node.ChildKey(1)
Esempio n. 8
0
    def key(self):
        """
        Returns the ledger key for this meteringpoint.

        :rtype: BIP32Key
        """
        return BIP32Key.fromExtendedKey(self.ledger_extended_key)
Esempio n. 9
0
def get_bip32_addrs(xpub):
    acc_node = BIP32Key.fromExtendedKey(xpub)
    i = 0
    while True:
        addr_node = acc_node.ChildKey(i)
        child_address = addr_node.Address()
        yield i, child_address
        i = i + 1
Esempio n. 10
0
    async def post(self):
        key_or_wif = self.get_secure_cookie("key_or_wif")
        if not key_or_wif and self.jwt.get('key_or_wif') != 'true':
            return self.render_as_json({'error': 'not authorized'})
        args = json.loads(self.request.body)
        if not args.get('uid'):
            return self.render_as_json({
                "error": True,
                "message": "no user account provided"
            })
        keyhash = hashlib.sha256(
            TU.generate_deterministic_signature(
                self.config, 'child_wallet').encode()).hexdigest()
        exkey = BIP32Key.fromExtendedKey(self.config.xprv)
        last_child_key = self.config.mongo.db.child_keys.find(
            {'signature': keyhash}, sort=[('inc', -1)])
        inc = last_child_key.count() + 1
        key = exkey.ChildKey(inc)
        child_key = BIP32Key.fromExtendedKey(key.ExtendedKey())
        child_key = child_key.ChildKey(inc)
        public_key = child_key.PublicKey().hex()
        address = str(
            P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(public_key)))
        private_key = child_key.PrivateKey().hex()
        wif = self.to_wif(private_key)

        await self.config.mongo.async_db.child_keys.insert_one({
            'account':
            args.get('uid'),
            'inc':
            inc,
            'extended':
            child_key.ExtendedKey(),
            'public_key':
            public_key,
            'address':
            address,
            'private_key':
            private_key,
            'wif':
            wif,
            'signature':
            keyhash
        })
        return self.render_as_json({"address": address})
Esempio n. 11
0
 def generate_keys(self):
     eth_btc_root_pub_key = get_root_key()
     eth_btc_root_key = BIP32Key.fromExtendedKey(eth_btc_root_pub_key, public=True)
     eth_btc_child_key = eth_btc_root_key.ChildKey(self.id)
     btc_address = eth_btc_child_key.Address()
     eth_address = keys.PublicKey(eth_btc_child_key.K.to_string()).to_checksum_address().lower()
     self.btc_address = btc_address
     self.eth_address = eth_address
     self.save()
Esempio n. 12
0
    def test_from_extended_key(self):
        extkey = 'xpub6BLBYTKDDbdgAmfVeZRE1VFTKCFtRv9CDkpUnSfrDiA3eN9NPPS8zLi4ykGgdQKoRvWhjnz6o1VffVGfjhdMnaby6Kmn8YLiJiCzuw8KugM'
        key = BIP32Key.fromExtendedKey(extkey)
        child = key.ChildKey(0).ChildKey(0)

        self.assertEqual('FjxiGJ7kkTHY1x3MBnZc9AHKFs9rRVUTKp', child.Address())
        self.assertEqual('020d54f0c23eb2f16d319e0168a9c7dfea90454f234b0b81359339db44d005e12a', child.PublicKey().encode('hex'))

        child = key.ChildKey(0).ChildKey(1)
        self.assertEqual('FZgDwnt2MbPPBtxNRLuG4xSxEvCeG11znT', child.Address())
        self.assertEqual('03e4e5e55b653cbe56555f31560df892b0d4ed967eae11754e6f35cedfc96e1fde', child.PublicKey().encode('hex'))
Esempio n. 13
0
def rootkey_from_seed(seed, network):
    if network == 'bitcoin' or network == 'ethereum':
        xprv = BIP32Key.fromEntropy(seed).ExtendedKey()
    elif network == 'bitcoin-testnet':
        xprv = BIP32Key.fromEntropy(seed, testnet=True).ExtendedKey()
    else:
        print("network should not be" + network)
        sys.exit(
            "Wrong Network : should be ethereum or bitcoin or bitcoin-testnet!"
        )
    rootkey = BIP32Key.fromExtendedKey(xprv)
    return rootkey
Esempio n. 14
0
def entropy2prvhex(entropy, derivation_path):
    """Entropy Bytes -> Private Key Hex"""
    from bip32utils import BIP32Key, BIP32_HARDEN
    assert isinstance(derivation_path, str), 'str_ should be str'
    path_list = derivation_path.split('/')
    assert path_list[0] == 'm', 'Derivation path should start with char "m"'

    xkey = BIP32Key.fromEntropy(entropy).ExtendedKey()
    key = BIP32Key.fromExtendedKey(xkey)
    for path in path_list[1:]:
        if path[-1] == "'":
            key = key.ChildKey(int(path[:-1]) + BIP32_HARDEN)
        else:
            key = key.ChildKey(int(path))
    return key.PrivateKey().hex()
Esempio n. 15
0
def xpub_to_uncompressed_pk(xpub):
    """
    Derive an uncompressed public key from an xpub. Let the excellent bip32utils library create the point from the xpub.
    :param xpub: Base58 encoded xpub.
    :return: Hex string uncompressed public key.
    """
    ec_point = BIP32Key.fromExtendedKey(xpub).K.pubkey.point

    def hx(i):
        without_prefix = hex(i)[2:]
        padding = 64 - len(
            without_prefix)  # values should be 32 bytes (64 hex chars)
        return (padding * "0") + without_prefix

    return '04' + hx(ec_point.x()) + hx(ec_point.y())
Esempio n. 16
0
def xpub_to_child_xpub(xpub, idx):
    """
    Get the child xpub for a given xpub and index. E.g. if `xp` is the xpub for m/44'/0'/0', then
    `xpub_to_child_xpub(xp, i)` will give the xpub corresponding to m/44'/0'/0'/i.
    :param xpub: Base58 encoded xpub.
    :param idx: Integer, non-hardened index (idx < 2**31).
    :return: Base58 encoded xpub.
    """
    assert 0 <= idx < MAX_IDX, \
        "Indexes must be >= 0 and < 2^31 (indexes >= 2^31 must be derived as hardened, which is not possible with an " \
        "xpub). "
    # TODO: This can return None if the left 32 bytes >= curve order or if point = Infinity (chances 1/2^127, but should be handled)
    # TODO: Replace object creation with faster implemenation
    # TODO: Try to simplify `ys = (x**3+7) % FIELD_ORDER` to pow(x, 3, FIELD_ORDER) + (7 % FIELD_ORDER) & check performance
    return BIP32Key.fromExtendedKey(xpub).CKDpub(idx).ExtendedKey(
        private=False)
    def generate_keys(self):
        eth_btc_root_public_key = HD_ROOT_KEYS['ETH-BTC']['public']
        root_key = BIP32Key.fromExtendedKey(eth_btc_root_public_key,
                                            public=True)
        child_key = root_key.ChildKey(self.id)

        self.btc_address = child_key.Address()
        self.eth_address = keys.PublicKey(
            child_key.K.to_string()).to_checksum_address().lower()

        duc_root_public_key = HD_ROOT_KEYS['DUC']['public']
        duc_root_key = DucatusWallet.deserialize(duc_root_public_key)
        self.duc_address = duc_root_key.get_child(self.id,
                                                  is_prime=False).to_address()

        self.save()
Esempio n. 18
0
def to_private_key(word):
    '''
	get private key from word!
	'''
    #generate seed from mnemonic word by mnemonic package
    m = mnemonic.Mnemonic("english")
    #xprv=m.to_hd_master_key(m.to_seed(words)) ;the same with BIP32Key.fromEntropy(seed)
    seed = m.to_seed(word)
    #generate extended private key(xprv) from seed
    key = BIP32Key.fromEntropy(seed)
    xprv = BIP32Key.fromEntropy(seed).ExtendedKey()
    # redefined key with extended private key
    key = BIP32Key.fromExtendedKey(xprv)
    #get the first account private for derivation path m/44'/60'/0'
    x=key.ChildKey(44 + BIP32_HARDEN) \
         .ChildKey(60 + BIP32_HARDEN) \
         .ChildKey(0 + BIP32_HARDEN) \
         .ChildKey(0) \
         .ChildKey(0) \
         .PrivateKey().hex()
    return x
Esempio n. 19
0
def main():
    import binascii
    import sys
    if len(sys.argv) > 1:
        data = sys.argv[1]
    else:
        data = sys.stdin.readline().strip()
    data = binascii.unhexlify(data)
    m = Mnemonic('english')
    
    # example mnemonic
    print("Mnemonic generated from entropy " + m.to_mnemonic(data))

    from bip32utils import BIP32Key
    print("\nExample mnemonic: " + "profit hood vibrant fiscal survey traffic quality rely soap fury helmet once")
    seed = m.to_seed("profit hood vibrant fiscal survey traffic quality rely soap fury helmet once")
    print("Seed " + seed.encode('hex'))
    key = BIP32Key.fromEntropy(seed)
    xprv = BIP32Key.fromEntropy(seed).ExtendedKey()
    print("Extended private key is " + xprv)
    
    # redefined key with extended private key 
    key = BIP32Key.fromExtendedKey(xprv)
    from bip32utils import BIP32_HARDEN
    # first address for derivation path m/44'/0'/0'
    print(key.ChildKey(44 + BIP32_HARDEN) \
         .ChildKey(0 + BIP32_HARDEN) \
         .ChildKey(0 + BIP32_HARDEN) \
         .ChildKey(0) \
         .ChildKey(0) \
         .Address())
    # second address for derivation path m/44'/0'/0'
    print(key.ChildKey(44 + BIP32_HARDEN) \
         .ChildKey(0 + BIP32_HARDEN) \
         .ChildKey(0 + BIP32_HARDEN) \
         .ChildKey(0) \
         .ChildKey(1) \
         .Address())
Esempio n. 20
0
 def get_bip32key(self) -> BIP32Key:
     if not self.__bip32_key:
         if not self.xpub:
             raise Exception('XPUB not set')
         self.__bip32_key = BIP32Key.fromExtendedKey(self.xpub)
     return self.__bip32_key
Esempio n. 21
0
def main():
    logo_show(True)

    # access
    if 'rpcusessl' in globals() and rpcusessl:
        import ssl
        ssl._create_default_https_context = ssl._create_unverified_context

        serverURL = 'https://' + rpcuser + ':' + rpcpassword + '@' + rpcbindip + \
            ':' + str(rpcport if USE_SSH_TUNNEL is False else SSH_LOCAL_PORT)

    else:
        serverURL = 'http://' + rpcuser + ':' + rpcpassword + '@' + rpcbindip + \
            ':' + str(rpcport if USE_SSH_TUNNEL is False else SSH_LOCAL_PORT)

    access = AuthServiceProxy(serverURL)

    if len(str(account_no)) == 0:
        err_msg = 'please configure bip32 path : account_no'
        print_err_exit(get_caller_name(), get_function_name(), err_msg)

    if TYPE_HW_WALLET.lower().startswith("ledgernanos"):
        client, signing, mpath = check_hw_wallet()

    else:
        client, signing, bip32, mpath, xpub = check_hw_wallet()

    if client is None:
        sys.exit()

    if TYPE_HW_WALLET.lower().startswith("ledgernanos"):

        try:

            print(
                '**** ====> use following address for 1K collateral of masternode'
            )

            for i in range(max_gab):
                addr_path = mpath + '/' + str(i)
                nodedata = client.getWalletPublicKey(addr_path)
                address = (nodedata.get('address')).decode("utf-8")

                addr_balance = round(
                    Decimal(
                        getaddressbalancewithoutexcept(address, access) / 1e8),
                    8)

                print(coin_name + ' address: ' + '{:20}'.format(addr_path) +
                      ' ' + address + ' ' + '{:13.8f}'.format(addr_balance))

            print()

        except AssertionError as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except KeyboardInterrupt:
            print_err_exit(get_caller_name(), get_function_name(),
                           "KeyboardInterrupt")

    else:
        keypath = mpath

        try:
            #bip32_path = client.expand_path(keypath)
            # xpub = bip32.serialize(
            #    client.get_public_node(bip32_path).node,
            #    (0x0488B21E if MAINNET else 0x043587CF))

            acc_node = BIP32Key.fromExtendedKey(xpub)

            print(
                '**** ====> use following address for 1K collateral of masternode'
            )

            for i in range(max_gab):
                child_path = '%s%s' % (keypath + '/', str(i))
                address = client.get_address(coin_name,
                                             client.expand_path(child_path))
                publicnode = client.get_public_node(
                    client.expand_path(child_path)).node.public_key.hex()

                # make sure xpub/tub
                bip32_addr_node = acc_node.ChildKey(i)
                bip32_address = bip32_addr_node.Address()
                bip32_addrpkey = bip32_addr_node.PublicKey().hex()

                addr_balance = round(
                    Decimal(
                        getaddressbalancewithoutexcept(address, access) / 1e8),
                    8)

                print(coin_name + ' address: ' + '{:20}'.format(child_path) +
                      ' ' + address + ' ' + '{:13.8f}'.format(addr_balance))

                assert bip32_address == address, "address mismatch, bip32 : %s <--> hw : %s" % (
                    bip32_address, address)
                assert publicnode == bip32_addrpkey, "pubkey mismatch, bip32 : %s <--> hw : %s" % (
                    bip32_addrpkey, publicnode)

            print()

        except AssertionError as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except KeyboardInterrupt:
            print_err_exit(get_caller_name(), get_function_name(),
                           "KeyboardInterrupt")
Esempio n. 22
0
        addr_node = chain_node.ChildKey(i)
        address = addr_node.Address()
        if process_address(desci, address):
            g = 0
        else:
            g += 1
        if g > gap:
            break
        i += 1


xpub = 'tpubDF8GkupYdvTQrsuL6HkCmpSJ7oENkKk9k7cRFuHQWrxca25pSBTq594ZebPxvwzQAdspYh5rd1nKz94TBhP4F2N1SqxqREk4ojXEQYCaYem'

addresses = []
gap = 10
acc_node = BIP32Key.fromExtendedKey(xpub)
process_chain('m/', acc_node)

#	./bip32test.py
#	m/0 yVUfEs2mdTrVsVRLZg9LoCp8sNBGc3p4FV
#	m/1 yfj8WoDP8sJNFSH8vr5pEEsQ8vZ2hCHped
#	m/2 yNXtJuijSCNPCbLZbcLHwZoUaD4RzMo19P
#	m/3 yQNVQdYosUHkk4wUjxzbLFEXfGqyGJXzXC
#	m/4 yTH5axsQ3X8YBiiEKPVY66n9choyEodcKC
#	m/5 yNAihSEJQH2hSbnUKRGWcn7LYij56VKPCP
#	m/6 yicVWrfJYDFAxUwTbdQnWjTjhre5dx4HBg
#	m/7 ySD94FvVzTtYNFmwirK4qE4jhtxjrVsoJ9
#	m/8 yRkY4zL4kJr7H7QqMtfDhNtxCeqU2uTqth
#	m/9 yQNwssFrbo2CtBrBCHt9D3ttaNLK6xDf7C
#	m/10 yPEuaemjx5TBnvQrpEKavrcb8MnL4XGRCA
Esempio n. 23
0
def derive_address(mpk, path = []):
    pub = BIP32Key.fromExtendedKey(mpk)
    for child_index in path:
        pub = pub.ChildKey(child_index)
    return pub.P2WPKHoP2SHAddress()
Esempio n. 24
0
def generate_keypool(args, wrpc, devices, start, end, internal, n_sigs, addrtype):
    pubkeys = []
    for d in devices:
        if 'core_wallet_name' in d:
            print("core")
            rpc = LoadWalletAndGetRPC(d['core_wallet_name'], d['rpcurl'])
            
            # Get 1000 pubkeys
            core_pubkeys = []
            for i in range(start, end + 1):
                addrinfo = rpc.getaddressinfo(rpc.getnewaddress())
                info = {addrinfo['pubkey'] : {addrinfo['hdmasterkeyid'] :addrinfo['hdkeypath']}}

                core_pubkeys.append(info)
            pubkeys.append(core_pubkeys)
        elif 'xpub' in d and 'fingerprint' in d:
            print("xpub")
            parent = BIP32Key.fromExtendedKey(d['xpub'])
            if internal:
                parent = parent.ChildKey(1)
                path_base = 'm/44h/0h/0h/1/'
            else:
                parent = parent.ChildKey(0)
                path_base = 'm/44h/0h/0h/0/'

            import_pubkeys = []
            for i in range(start, end + 1):
                this_import = {}
                path = path_base + str(i)

                child = parent.ChildKey(i)
                address = child.Address()

                import_pubkeys.append({binascii.hexlify(child.PublicKey()).decode() : {d['fingerprint'] : path}})
            pubkeys.append(import_pubkeys)
        else:
            print("HWW")
            # Common for all hww
            hwi_args = []
            if args.testnet or args.regtest:
                hwi_args.append('--testnet')
            hwi_args.append('-f')
            hwi_args.append(d['fingerprint'])
            if 'password' in d:
                hwi_args.append('-p')
                hwi_args.append(d['password'])
            hwi_args.append('getkeypool')
            if internal:
                hwi_args.append('m/44h/0h/0h/1')
            else:
                hwi_args.append('m/44h/0h/0h/0')
            hwi_args.append(str(start))
            hwi_args.append(str(end))
            importkeys = hwi_command(hwi_args)

            pubkeys.append(ProcessImportMultiString(importkeys))

    print("Getting multisig keys")
    multisig_keys = []
    for i in range(start, end + 1):
        multisig_keys.append([])
    for pubkey_list in pubkeys:
        i = 0
        for pubkey in pubkey_list:
            multisig_keys[i].append(pubkey)
            i += 1

    print("Getting Multisig addresses")
    ms_addrs = []
    for keys in multisig_keys:
        cms_list = []
        for key in keys:
            [(pubkey, origin)] = key.items()
            cms_list.append(pubkey)
        ms = wrpc.addmultisigaddress(n_sigs, cms_list, '', addrtype)
        ms_addrs.append(ms['address'])

        # Make import multi object
        this_import = {}
        this_import['scriptPubKey'] = {'address' : ms['address']}
        this_import['redeemscript'] = ms['redeemScript']
        this_import['pubkeys'] = keys
        this_import['timestamp'] = 'now'
        this_import['keypool'] = False
        this_import['watch_only'] = True
        this_import['internal'] = internal
        wrpc.importmulti([this_import])

    return ms_addrs
Esempio n. 25
0
def private_key_from_xprv(x_private_key):
    private_key = BIP32Key.fromExtendedKey(x_private_key)
    return binascii.b2a_hex(private_key.PrivateKey())
Esempio n. 26
0
if __name__ == '__main__':

    m = Mnemonic('english')
    words = m.generate(strength=256)
    print(words)

    seed = m.to_seed(words)
    print("************")
    print("Seed " + seed.hex())
    #key = BIP32Key.fromEntropy(seed)

    print("******************Test Bitcoin********************")
    globalkey = BIP32Key.fromEntropy(seed)
    root = globalkey.ExtendedKey()
    print("Root Key is " + root)
    key = BIP32Key.fromExtendedKey(root)
    bitcoinkey = key.ChildKey(44 + BIP32_HARDEN) \
        .ChildKey(0 + BIP32_HARDEN) \
        .ChildKey(0 + BIP32_HARDEN)
    AccountExtendedPrivateKey = bitcoinkey.ExtendedKey()
    print("Account Extended Private Key is " + AccountExtendedPrivateKey)
    AccountExtendedPublicKey = bitcoinkey.ExtendedKey(private=False)
    print("Account Extended Public Key is " + AccountExtendedPublicKey)
    bitcoinaccount = bitcoinkey.ChildKey(0)
    BIP32ExtendedPrivateKey = bitcoinaccount.ExtendedKey()
    print("BIP32 Extended Private Key  is : " + BIP32ExtendedPrivateKey)
    BIP32ExtendedPublicKey = bitcoinaccount.ExtendedKey(private=False)
    print("BIP32 Extended Public Key  is : " + BIP32ExtendedPublicKey)
    bitcoin0 = bitcoinaccount.ChildKey(0)

    print("first private key")
Esempio n. 27
0
def get_wallet_from_xpub(xpub, no):
    return BIP32Key.fromExtendedKey(xpub).ChildKey(0).ChildKey(no).Address()
Esempio n. 28
0
    def generate(cls,
                 xprv=None,
                 prv=None,
                 seed=None,
                 child=None,
                 username=None,
                 mongodb_host=None,
                 db_name=None):
        mnemonic = Mnemonic('english')
        # generate 12 word mnemonic seed
        if not seed and not xprv and not prv:
            seed = mnemonic.generate(256)
        private_key = None
        if seed:
            # create new wallet
            entropy = mnemonic.to_entropy(seed)
            key = BIP32Key.fromEntropy(entropy)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
            public_key = PublicKey.from_point(
                key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex()
            address = str(key.Address())

        if prv:
            key = PrivateKey.from_hex(prv)
            private_key = key.to_hex()
            extended_key = ''
            public_key = key.public_key.format().hex()
            address = str(
                P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(public_key)))

        if xprv:
            key = BIP32Key.fromExtendedKey(xprv)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
            public_key = PublicKey.from_point(
                key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex()
            address = str(key.Address())

        if xprv and child:
            for x in child:
                key = key.ChildKey(int(x))
                private_key = key.PrivateKey().hex()
                public_key = PublicKey.from_point(
                    key.K.pubkey.point.x(),
                    key.K.pubkey.point.y()).format().hex()
                address = str(key.Address())

        if not private_key:
            raise Exception('No key')

        try:
            u = UPnP(None, None, 200, 0)
            u.discover()
            u.selectigd()
            peer_host = u.externalipaddress()
        except:
            try:
                import urllib.request
                peer_host = urllib.request.urlopen(
                    'https://ident.me').read().decode('utf8')
            except:
                peer_host = ''

        return cls({
            "modes": ['node', 'web', 'pool'],
            "root_app": '',
            "seed": seed or '',
            "xprv": extended_key or '',
            "private_key": private_key,
            "wif": cls.generate_wif(private_key),
            "public_key": public_key,
            "address": address,
            "api_whitelist": [],
            "serve_host": "0.0.0.0",
            "serve_port": 8001,
            "use_pnp": False,
            "ssl": False,
            "origin": '',
            "sia_api_key": '',
            "post_peer": False,
            "peer_host": peer_host,
            "peer_port": 8000,
            "peer_type": "user",
            "peer": "http://localhost:8000",
            "callbackurl": "http://0.0.0.0:8001/create-relationship",
            "jwt_public_key": None,
            "fcm_key": "",
            "database": db_name or "yadacoin",
            "site_database": db_name + "site" if db_name else "yadacoinsite",
            "mongodb_host": mongodb_host or "localhost",
            "mixpanel": "",
            "username": username or '',
            "network": "mainnet",
            "wallet_host_port": 'http://localhost:8001',
            "credits_per_share": 5,
            "shares_required": False,
            "pool_payout": False,
            "pool_take": .01,
            "payout_frequency": 6
        })
Esempio n. 29
0
def bip32_getaddress(xpub, index_no):
    assert isinstance(index_no, int)
    acc_node = BIP32Key.fromExtendedKey(xpub)
    addr_node = acc_node.ChildKey(index_no)
    address = addr_node.Address()
    return address
Esempio n. 30
0
def get_private_keys(root_private_key, child_id):
    root = BIP32Key.fromExtendedKey(root_private_key)
    eth_private = keys.PrivateKey(root.ChildKey(child_id).k.to_string())
    btc_private = root.ChildKey(child_id).WalletImportFormat()
    return eth_private, btc_private
Esempio n. 31
0
def main():
    logo_show(True)

    if TYPE_HW_WALLET.lower().startswith("ledgernanos"):
        client, signing, mpath = check_hw_wallet()

    else:
        client, signing, bip32, mpath, xpub = check_hw_wallet()

    if client is None:
        sys.exit()

    if TYPE_HW_WALLET.lower().startswith("ledgernanos"):

        try:
            print(
                '**** ====> use following address for 1K collateral of masternode'
            )

            for i in range(max_gab):
                addr_path = mpath + '/' + str(i)
                nodedata = client.getWalletPublicKey(addr_path)
                address = (nodedata.get('address')).decode("utf-8")

                print('Dash' + ' address: ' + '{:20}'.format(addr_path) + ' ' +
                      address)

            print()

        except AssertionError as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except KeyboardInterrupt:
            print_err_exit(get_caller_name(), get_function_name(),
                           "KeyboardInterrupt")

    else:
        keypath = mpath
        printdbg('main : keypath : %s' % keypath)
        printdbg('main : xpub[:7] : %s' % xpub[:7])
        printdbg('main : xpub[-7:] : %s' % xpub[-7:])

        try:
            #bip32_path = client.expand_path(keypath)
            # xpub = bip32.serialize(
            #    client.get_public_node(bip32_path).node,
            #    (0x0488B21E if MAINNET else 0x043587CF))

            acc_node = BIP32Key.fromExtendedKey(xpub)

            print(
                '**** ====> use following address for 1K collateral of masternode'
            )

            for i in range(max_gab):
                child_path = '%s%s' % (keypath + '/', str(i))
                address = client.get_address(coin_name,
                                             client.expand_path(child_path))
                publicnode = client.get_public_node(
                    client.expand_path(child_path)).node.public_key.hex()

                # make sure xpub/tub
                bip32_addr_node = acc_node.ChildKey(i)
                bip32_address = bip32_addr_node.Address()
                bip32_addrpkey = bip32_addr_node.PublicKey().hex()

                #print(address, bip32_addrpkey, publicnode)
                # print(publicnode)

                print(coin_name + ' address: ' + '{:20}'.format(child_path) +
                      ' ' + address)

                assert bip32_address == address, "address mismatch, bip32 : %s <--> hw : %s" % (
                    bip32_address, address)
                assert publicnode == bip32_addrpkey, "pubkey mismatch, bip32 : %s <--> hw : %s" % (
                    bip32_addrpkey, publicnode)

            print()

        except AssertionError as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except Exception as e:
            err_msg = str(e.args)
            print_err_exit(get_caller_name(), get_function_name(), err_msg)

        except KeyboardInterrupt:
            print_err_exit(get_caller_name(), get_function_name(),
                           "KeyboardInterrupt")

        client.close()
Esempio n. 32
0
def get_wallet_from_xpub(xpub, no):
    return BIP32Key.fromExtendedKey(xpub).ChildKey(0).ChildKey(no).Address()