def create_invoice_user (email):
	cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
	cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM user WHERE email = %s AND active = 1", (email))
	result = False
	for row in cur.fetchall():
		result = row
	if result:
		if result['masterpubkey_btc'][0:4] == "xpub":
			# BIP44
			dpk1 = bitcoin.bip32_ckd(result['masterpubkey_btc'], 0)
			dpk2 = bitcoin.bip32_ckd(dpk1, result['offset_btc'])
			pubkey = bitcoin.bip32_extract_key(dpk2)
		else:
			# Electrum 1.x
			pubkey = bitcoin.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc'])
		address = bitcoin.pubkey_to_address(pubkey)
		bitcoind_importaddress(address)
		cur.execute ("UPDATE user SET offset_btc = offset_btc + 1 WHERE email = %s AND active = 1 AND masterpubkey_btc = %s", (email, result['masterpubkey_btc']))
		if result['feecurrency'] in ("USD", "GBP", "EUR"):
			result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency']))
		cur.execute ("INSERT INTO invoice (issuer, address, coin, amount, type, paid) VALUES (%s, %s, 'BTC', %s, 1, 0)", (result['bm'], address, result['feeamount']))
		cur.close()
		return address, result['feeamount'];
	cur.close()
	return False
Exemple #2
0
    def __init__(self,
                 seedarg,
                 max_mix_depth=2,
                 gaplimit=6,
                 extend_mixdepth=False,
                 storepassword=False):
        super(Wallet, self).__init__()
        self.max_mix_depth = max_mix_depth
        self.storepassword = storepassword
        # key is address, value is (mixdepth, forchange, index) if mixdepth =
        #  -1 it's an imported key and index refers to imported_privkeys
        self.addr_cache = {}
        self.unspent = {}
        self.spent_utxos = []
        self.imported_privkeys = {}
        self.seed = self.read_wallet_file_data(seedarg)
        if extend_mixdepth and len(self.index_cache) > max_mix_depth:
            self.max_mix_depth = len(self.index_cache)
        self.gaplimit = gaplimit
        master = btc.bip32_master_key(self.seed)
        m_0 = btc.bip32_ckd(master, 0)
        mixing_depth_keys = [btc.bip32_ckd(m_0, c)
                             for c in range(self.max_mix_depth)]
        self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1))
                     for m in mixing_depth_keys]

        # self.index = [[0, 0]]*max_mix_depth
        self.index = []
        for i in range(self.max_mix_depth):
            self.index.append([0, 0])
def create_invoice_domain (domain, payer):
	cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor)
	filterwarnings('ignore', category = MySQLdb.Warning)
	cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain))
	result = False
	for row in cur.fetchall():
		result = row
	while result:
		if result['masterpubkey_btc'][0:4] == "xpub":
			# BIP44
			dpk1 = bitcoin.bip32_ckd(result['masterpubkey_btc'], 0)
			dpk2 = bitcoin.bip32_ckd(dpk1, result['offset_btc'])
			pubkey = bitcoin.bip32_extract_key(dpk2)
		else:
			# Electrum 1.x
			pubkey = bitcoin.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc'])
		address = bitcoin.pubkey_to_address(pubkey)
		bitcoind_importaddress(address)
		cur.execute ("UPDATE domain SET offset_btc = offset_btc + 1 WHERE name = %s AND active = 1 AND masterpubkey_btc = %s", (domain, result['masterpubkey_btc']))
		if result['feecurrency'] in ("USD", "GBP", "EUR"):
			result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency']))
		cur.execute ("INSERT IGNORE INTO invoice (issuer, payer, address, coin, amount, type, paid) VALUES (%s, %s, %s, 'BTC', %s, 0, 0)", (result['bm'], payer, address, result['feeamount']))

		# invoice already exists for that address, increment
		if cur.rowcount == 0:
			cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain))
			result = False
			for row in cur.fetchall():
				result = row
			continue
		
		cur.close()
		return address, result['feeamount'];
	cur.close()
	return False
Exemple #4
0
 def _derive_address(self, change_or_deposit, index, master_key):
     xpriv = bip32_ckd(
         bip32_ckd(self.get_bip44_master(master_key), change_or_deposit),
         index)
     priv = bip32_extract_key(xpriv)
     address = privtoaddr(priv, self.get_address_byte())
     return address, priv
Exemple #5
0
    def _generate_new_keypair(self):

        seed = str(random.randrange(2 ** 256))

        # Deprecated (pre-BIP32)
        # self.secret = hashlib.sha256(secret).hexdigest()
        # self.pubkey = privkey_to_pubkey(self.secret)
        # self.log.debug('Keys %s %s', self.secret, self.pubkey)

        # Move to BIP32 keys m/0/0/0
        wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0)
        wallet_chain = bitcoin.bip32_ckd(wallet, 0)
        bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0)
        identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv)
        bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
        identity_pub = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(bip32_identity_pub), 'hex')

        self.pubkey = identity_pub
        self.secret = identity_priv

        new_settings = {
            "secret": self.secret,
            "pubkey": self.pubkey,
            "bip32_seed": seed
        }
        self.db_connection.update_entries("settings", new_settings, {"market_id": self.market_id})
        self.settings.update(new_settings)
Exemple #6
0
 def __init__(self,
              seedarg,
              max_mix_depth=2,
              gaplimit=6,
              extend_mixdepth=False,
              storepassword=False,
              pwd=None):
     super(Wallet, self).__init__()
     self.max_mix_depth = max_mix_depth
     self.storepassword = storepassword
     # key is address, value is (mixdepth, forchange, index) if mixdepth =
     #  -1 it's an imported key and index refers to imported_privkeys
     self.addr_cache = {}
     self.unspent = {}
     self.spent_utxos = []
     self.imported_privkeys = {}
     self.decrypted = False
     self.seed = self.read_wallet_file_data(seedarg, pwd)
     if not self.seed:
         return
     if extend_mixdepth and len(self.index_cache) > max_mix_depth:
         self.max_mix_depth = len(self.index_cache)
     self.gaplimit = gaplimit
     master = btc.bip32_master_key(self.seed,
                                   (btc.MAINNET_PRIVATE if get_network()
                                    == 'mainnet' else btc.TESTNET_PRIVATE))
     m_0 = btc.bip32_ckd(master, 0)
     mixing_depth_keys = [
         btc.bip32_ckd(m_0, c) for c in range(self.max_mix_depth)
     ]
     self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1))
                  for m in mixing_depth_keys]
     self.init_index()
    def save_settings(self):
        #no settings to save if there is no master key
        if self.settingsStore['bip32master'] is None:
            self.changed = False
            return

        account = self.settingsWindow.accountKeyButton.get_value_as_int()
        self.settingsStore["accountNumber"] = account

        #if there is no info for this account, we have to derive the master key for it
        if (account not in self.settingsStore['accounts']):
            self.settingsStore['accounts'][account] = {}
            accountHardenedKey = bitcoin.bip32_ckd(
                self.settingsStore['bip32master'], (account + 2**31))
            #we always work with the 'external' chain, since we don't support multiple chains in an account
            accountKey = bitcoin.bip32_ckd(accountHardenedKey, 0)
            self.settingsStore['accounts'][account]['accountKey'] = accountKey

        #update the number of keys
        numKeys = self.settingsWindow.numKeysEntry.get_value_as_int()
        self.settingsStore['accounts'][account]['numKeys'] = numKeys
        Settings.Instance().save_config_file(self.settingsStore)

        self.changed = False
        return
Exemple #8
0
    def __init__(self, seedarg, max_mix_depth=2, gaplimit=6):
        super(Wallet, self).__init__()
        self.max_mix_depth = max_mix_depth
        self.gaplimit = gaplimit
        self.seed = self.get_seed(seedarg)
        master = btc.bip32_master_key(self.seed)
        m_0 = btc.bip32_ckd(master, 0)
        mixing_depth_keys = [
            btc.bip32_ckd(m_0, c) for c in range(max_mix_depth)
        ]
        self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1))
                     for m in mixing_depth_keys]

        #self.index = [[0, 0]]*max_mix_depth
        self.index = []
        for i in range(max_mix_depth):
            self.index.append([0, 0])

        #example
        #index = self.index[mixing_depth]
        #key = btc.bip32_ckd(self.keys[mixing_depth][index[0]], index[1])

        self.addr_cache = {}
        self.unspent = {}
        self.spent_utxos = []
Exemple #9
0
    def _generate_new_keypair(self):

        seed = str(random.randrange(2**256))

        # Deprecated (pre-BIP32)
        # self.secret = hashlib.sha256(secret).hexdigest()
        # self.pubkey = privkey_to_pubkey(self.secret)
        # self.log.debug('Keys %s %s', self.secret, self.pubkey)

        # Move to BIP32 keys m/0/0/0
        wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0)
        wallet_chain = bitcoin.bip32_ckd(wallet, 0)
        bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0)
        identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv)
        bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
        identity_pub = bitcoin.encode_pubkey(
            bitcoin.bip32_extract_key(bip32_identity_pub), 'hex')

        self.pubkey = identity_pub
        self.secret = identity_priv

        new_settings = {
            "secret": self.secret,
            "pubkey": self.pubkey,
            "bip32_seed": seed
        }
        self.db_connection.update_entries("settings", new_settings,
                                          {"market_id": self.market_id})
        self.settings.update(new_settings)
Exemple #10
0
 def __init__(self,
              seedarg,
              max_mix_depth=2,
              gaplimit=6,
              extend_mixdepth=False,
              storepassword=False,
              pwd = None):
     super(Wallet, self).__init__()
     self.max_mix_depth = max_mix_depth
     self.storepassword = storepassword
     # key is address, value is (mixdepth, forchange, index) if mixdepth =
     #  -1 it's an imported key and index refers to imported_privkeys
     self.addr_cache = {}
     self.unspent = {}
     self.spent_utxos = []
     self.imported_privkeys = {}
     self.decrypted = False
     self.seed = self.read_wallet_file_data(seedarg, pwd)
     if not self.seed:
         return
     if extend_mixdepth and len(self.index_cache) > max_mix_depth:
         self.max_mix_depth = len(self.index_cache)
     self.gaplimit = gaplimit
     self.master_key = btc.bip32_master_key(self.seed, (btc.MAINNET_PRIVATE if
         get_network() == 'mainnet' else btc.TESTNET_PRIVATE))
     m_0 = btc.bip32_ckd(self.master_key, 0)
     self.mixing_depth_keys = [btc.bip32_ckd(m_0, c)
                          for c in range(self.max_mix_depth)]
     self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1))
                  for m in self.mixing_depth_keys]
     self.init_index()
 def __init__(self, mpk):
     super(SingleSigWallet, self).__init__()
     try:
         self.branches = (btc.bip32_ckd(mpk, 0), btc.bip32_ckd(mpk, 1))
     except Exception:
         raise ValueError("Bad master public key format. Get it from " +
                          "Electrum menu `Wallet` -> `Information`")
Exemple #12
0
def test_ckd_pubkeys():
    pub = 'xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw'
    new_pub = btc.bip32_ckd(pub, 4)
    #how to check it's right?
    print new_pub
    #try to do on hardened, should fail, that's the idea:
    with pytest.raises(Exception) as e_info:
        new_pub = btc.bip32_ckd(pub, 2**31+1)
Exemple #13
0
def mnemonic_to_hdkey(mnemonic):
    # if we wanted to avoid the mnemonic dep we could just do: 
    #  pbkdf2_hmac('sha512', mnemonic, 'mnemonic', 2048).encode('hex')
    # to get the seed
    if not Mnemonic('english').check(mnemonic):
        raise Exception('invalid mnemonic')
    seed = Mnemonic('english').to_seed(mnemonic)
    hd_root = bip32_master_key(seed)
    # path is m/0'/0'/0'
    return bip32_ckd(bip32_ckd(bip32_ckd(hd_root, 2**31), 2**31), 2**31)
Exemple #14
0
def getPrivKey(xpriv, i):
    privkeys = {}
    priv0 = bitcoin.bip32_ckd(xpriv, 0)

    privateKey = bitcoin.bip32_ckd(priv0, i)
    wifKey = bitcoin.encode_privkey(bitcoin.bip32_extract_key(privateKey), 'wif_compressed')
    address_fromPriv =  bitcoin.privtoaddr(wifKey)
    privkeys[address_fromPriv] = wifKey

    return privkeys
 def __init__(self, m, mpk_list):
     super(MultisigWallet, self).__init__()
     self.m = m
     try:
         self.pubkey_branches = [(btc.bip32_ckd(mpk,
                                                0), btc.bip32_ckd(mpk, 1))
                                 for mpk in mpk_list]
     except Exception:
         raise ValueError("Bad master public key format. Get it from " +
                          "Electrum menu `Wallet` -> `Information`")
Exemple #16
0
def getAddressesFromXPUB(xpub, i=10):
    addressList = []
    pub0 = bitcoin.bip32_ckd(xpub, 0)

    for i in range (0, i):
        publicKey = bitcoin.bip32_ckd(pub0, i)
        hexKey = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(publicKey), 'hex_compressed')
        address_fromPub =  bitcoin.pubtoaddr(hexKey)
        addressList.append(address_fromPub)

    return addressList
 def regenerate_keys( account_key, needed_keys, key_list ):
     for key in needed_keys:
         return_key = bitcoin.bip32_ckd(account_key, key)
         return_key = bitcoin.bip32_extract_key(return_key)
         return_key = bitcoin.privtopub(return_key)
         key_list.append( ( key, return_key, False ) )
     return 
    def get_next_public_key(  ):
        settings = Settings.Instance().get_settings_json()

        if( settings['bip32master'] is None ):
            raise RuntimeError( "Master key has not been set up yet" )

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain( settings )

        return_key = bitcoin.bip32_ckd( account_key, key_number )
        return_key = bitcoin.bip32_extract_key( return_key )
        return_key = bitcoin.privtopub( return_key )

        #save key for later
        if 'keys' not in settings['accounts'][account_number]:
            settings['accounts'][account_number]['keys'] = []
        settings['accounts'][account_number]['keys'].append( (key_number, return_key, False ) )
        
        #we increment the key counter after making the key
        #because the chain code is 0 indexed, making the 0th key 
        #the first one we use
        key_number += 1

        #remember to save our new key
        settings['accounts'][account_number]['numKeys'] = key_number
        Settings.Instance().save_config_file( settings )

        return return_key
 def get_private_for_chain(account, key_number, settings=None):
     if settings is None:
         settings = Settings.Instance().get_settings_json()
     account_key = settings['accounts'][account]['accountKey']
     return_key = bitcoin.bip32_ckd( account_key, key_number )
     return_key = bitcoin.bip32_extract_key( return_key )
     return return_key
    def get_bip32_key( public_keys ):
        settings = Settings.Instance().get_settings_json()

        if( settings['bip32master'] is None ):
            return None

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain( settings )

        #see if we already have this cached, and I can just get the key fast
        cached = set( settings['accounts'][account_number].get(keys,[]) )
        pub_set = set( public_keys )
        hits = cached & pub_set 

        if len(hits) > 0:
            return KeyHelper.get_private_for_chain( account_number, hits[0][0], settings )

        #drat, didn't find it! at least we can only need to test the ones that 
        #we didn't already check
        missed = set(range(key_number)) - set([cache[0] for cache in cached])
            
        for i in missed:
            priv = bitcoin.bip32_ckd( account_key, i )
            priv = bitcoin.bip32_extract_key( priv )
            canidate = bitcoin.privtopub( priv )
            if( canidate in public_keys ):
                return priv

        return None
Exemple #21
0
 def regenerate_keys(account_key, needed_keys, key_list):
     for key in needed_keys:
         return_key = bitcoin.bip32_ckd(account_key, key)
         return_key = bitcoin.bip32_extract_key(return_key)
         return_key = bitcoin.privtopub(return_key)
         key_list.append((key, return_key, False))
     return
Exemple #22
0
    def do_cosign(self, args):
        if not self.seed:
            raise Exception("cosign: Load or generate a seed first")

        if not self.recovery_package:
            raise Exception(
                "cosign: Load a recovery package first (load_recovery)")

        path = None
        if args and len(args.split()) > 0:
            path = args.split()[0]

        master_xpriv = self.seed.as_HD_root()

        if path:
            path = [
                2**31 +
                int(child[:-1]) if child[-1:] in "hp'HP" else int(child)
                for child in path.split('/')
            ]
            for p in path:
                master_xpriv = bitcoin.bip32_ckd(master_xpriv, p)

        self.recovery_package = recovery.cosign(master_xpriv,
                                                self.recovery_package)
Exemple #23
0
 def get_private_for_chain(account, key_number, settings=None):
     if settings is None:
         settings = Settings.Instance().get_settings_json()
     account_key = settings['accounts'][account]['accountKey']
     return_key = bitcoin.bip32_ckd(account_key, key_number)
     return_key = bitcoin.bip32_extract_key(return_key)
     return return_key
Exemple #24
0
    def get_next_public_key():
        settings = Settings.Instance().get_settings_json()

        if (settings['bip32master'] is None):
            raise RuntimeError("Master key has not been set up yet")

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain(
            settings)

        return_key = bitcoin.bip32_ckd(account_key, key_number)
        return_key = bitcoin.bip32_extract_key(return_key)
        return_key = bitcoin.privtopub(return_key)

        #save key for later
        if 'keys' not in settings['accounts'][account_number]:
            settings['accounts'][account_number]['keys'] = []
        settings['accounts'][account_number]['keys'].append(
            (key_number, return_key, False))

        #we increment the key counter after making the key
        #because the chain code is 0 indexed, making the 0th key
        #the first one we use
        key_number += 1

        #remember to save our new key
        settings['accounts'][account_number]['numKeys'] = key_number
        Settings.Instance().save_config_file(settings)

        return return_key
Exemple #25
0
    def get_bip32_key(public_keys):
        settings = Settings.Instance().get_settings_json()

        if (settings['bip32master'] is None):
            return None

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain(
            settings)

        #see if we already have this cached, and I can just get the key fast
        cached = set(settings['accounts'][account_number].get(keys, []))
        pub_set = set(public_keys)
        hits = cached & pub_set

        if len(hits) > 0:
            return KeyHelper.get_private_for_chain(account_number, hits[0][0],
                                                   settings)

        #drat, didn't find it! at least we can only need to test the ones that
        #we didn't already check
        missed = set(range(key_number)) - set([cache[0] for cache in cached])

        for i in missed:
            priv = bitcoin.bip32_ckd(account_key, i)
            priv = bitcoin.bip32_extract_key(priv)
            canidate = bitcoin.privtopub(priv)
            if (canidate in public_keys):
                return priv

        return None
Exemple #26
0
 def bip32_descend(*args):
     if len(args) == 2 and isinstance(args[1], list):
         key, path = args
     else:
         key, path = args[0], map(int, args[1:])
     for p in path:
         key = bitcoin.bip32_ckd(key, p)
     return key
def derive_childkey(key, chaincode, prefix=bitcoin.MAINNET_PUBLIC):
    """
    Given a 33 byte public key and 32 byte chaincode (both in hex) derive the first child key.
    """

    master_key = bitcoin.bip32_serialize((prefix, 0, b"\x00" * 4, 0, unhexlify(chaincode), unhexlify(key)))
    child_key = bitcoin.bip32_ckd(master_key, 0)
    return bitcoin.bip32_extract_key(child_key)
Exemple #28
0
def bip32_child(key, path):
    path = [
        2**31 + int(child[:-1]) if child[-1:] in "hp'HP" else int(child)
        for child in path.split('/')
    ]
    for p in path:
        key = bitcoin.bip32_ckd(key, p)
    return key
def derive_childkey(key, chaincode, prefix=bitcoin.MAINNET_PUBLIC):
    """
    Given a 33 byte public key and 32 byte chaincode (both in hex) derive the first child key.
    """

    master_key = bitcoin.bip32_serialize((prefix, 0, b'\x00'*4, 0,
                                          unhexlify(chaincode), unhexlify(key)))
    child_key = bitcoin.bip32_ckd(master_key, 0)
    return bitcoin.bip32_extract_key(child_key)
def getXPRIVKeys(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase

    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))

    priv = bitcoin.bip32_master_key(unhexlify(seed))

    account = 0
    #derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account)

    xprivs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+i)
        xprivs.append(derivedPrivateKey)

    return xprivs
Exemple #31
0
	def __init__(self, seedarg, max_mix_depth=2):
		self.max_mix_depth = max_mix_depth
		self.seed = self.get_seed(seedarg)
		master = btc.bip32_master_key(self.seed)
		m_0 = btc.bip32_ckd(master, 0)
		mixing_depth_keys = [btc.bip32_ckd(m_0, c) for c in range(max_mix_depth)]
		self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in mixing_depth_keys]

		#self.index = [[0, 0]]*max_mix_depth
		self.index = []
		for i in range(max_mix_depth):
			self.index.append([0, 0])

		#example
		#index = self.index[mixing_depth]
		#key = btc.bip32_ckd(self.keys[mixing_depth][index[0]], index[1])

		self.addr_cache = {}
		self.unspent = {}
		self.spent_utxos = []
Exemple #32
0
def get_next_address(send_job):
    if 'addresses' in send_job:
        this_index = send_job['index']
        send_job['index'] = (send_job['index'] + 1) % len(send_job['addresses'])
        return send_job['addresses'][this_index]
    elif 'xpub' in send_job:
        send_job['index'] += 1
        return btc.pubtoaddr(btc.bip32_extract_key(btc.bip32_ckd(
            send_job['xpub'], send_job['index']-1)), get_p2pk_vbyte())
    else:
        assert False
Exemple #33
0
    def get_signing_key(self, contract_id):
        # Get BIP32 child signing key for this order id
        rows = self.db_connection.select_entries("keystore", {
            'contract_id': contract_id
        })

        if len(rows):
            key_id = rows[0]['id']

            settings = self.get_settings()

            wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(settings.get('bip32_seed')), 1)
            wallet_chain = bitcoin.bip32_ckd(wallet, 0)
            bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, key_id)
            # bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
            return bitcoin.encode_privkey(bitcoin.bip32_extract_key(bip32_identity_priv), 'wif')

        else:
            self.log.error('No keys found for that contract id: #%s', contract_id)
            return
Exemple #34
0
def getXPRIVKeys(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase

    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))

    priv = bitcoin.bip32_master_key(unhexlify(seed))

    account = 0
    #derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account)

    xprivs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(
            bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED),
                              HARDENED), HARDENED + i)
        xprivs.append(derivedPrivateKey)

    return xprivs
Exemple #35
0
    def _generate_new_keypair(self):

        seed = str(random.randrange(2**256))

        # Deprecated (pre-BIP32)
        # self.secret = hashlib.sha256(secret).hexdigest()
        # self.pubkey = privkey_to_pubkey(self.secret)
        # self.log.debug('Keys %s %s', self.secret, self.pubkey)

        # Move to BIP32 keys m/0/0/0
        wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0)
        wallet_chain = bitcoin.bip32_ckd(wallet, 0)
        bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0)
        identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv)
        bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
        identity_pub = bitcoin.encode_pubkey(
            bitcoin.bip32_extract_key(bip32_identity_pub), 'hex')

        self.pubkey = identity_pub
        self.secret = identity_priv

        # Generate SIN
        sha_hash = hashlib.sha256()
        sha_hash.update(self.pubkey)
        ripe_hash = hashlib.new('ripemd160')
        ripe_hash.update(sha_hash.digest())

        self.guid = ripe_hash.hexdigest()
        self.sin = obelisk.EncodeBase58Check('\x0F\x02%s' % ripe_hash.digest())

        newsettings = {
            "secret": self.secret,
            "pubkey": self.pubkey,
            "guid": self.guid,
            "sin": self.sin,
            "bip32_seed": seed
        }
        self.db_connection.update_entries("settings", newsettings,
                                          {"market_id": self.market_id})
        self.settings.update(newsettings)
Exemple #36
0
    def generate_new_pubkey(self, contract_id):
        self.log.debug('Generating new pubkey for contract')

        # Retrieve next key id from DB
        next_key_id = len(self.db_connection.select_entries("keystore", select_fields="id")) + 1

        # Store updated key in DB
        self.db_connection.insert_entry(
            "keystore",
            {
                'contract_id': contract_id
            }
        )

        # Generate new child key (m/1/0/n)
        wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(self.settings.get('bip32_seed')), 1)
        wallet_chain = bitcoin.bip32_ckd(wallet, 0)
        bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, next_key_id)
        bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
        pubkey = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(bip32_identity_pub), 'hex')

        return pubkey
Exemple #37
0
    def generate_new_pubkey(self, contract_id):
        self.log.debug('Generating new pubkey for contract')

        # Retrieve next key id from DB
        next_key_id = len(
            self.db_connection.select_entries("keystore",
                                              select_fields="id")) + 1

        # Store updated key in DB
        self.db_connection.insert_entry("keystore",
                                        {'contract_id': contract_id})

        # Generate new child key (m/1/0/n)
        wallet = bitcoin.bip32_ckd(
            bitcoin.bip32_master_key(self.settings.get('bip32_seed')), 1)
        wallet_chain = bitcoin.bip32_ckd(wallet, 0)
        bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, next_key_id)
        bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
        pubkey = bitcoin.encode_pubkey(
            bitcoin.bip32_extract_key(bip32_identity_pub), 'hex')

        return pubkey
Exemple #38
0
    def _generate_new_keypair(self):

        seed = str(random.randrange(2 ** 256))

        # Deprecated (pre-BIP32)
        # self.secret = hashlib.sha256(secret).hexdigest()
        # self.pubkey = privkey_to_pubkey(self.secret)
        # self.log.debug('Keys %s %s', self.secret, self.pubkey)

        # Move to BIP32 keys m/0/0/0
        wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0)
        wallet_chain = bitcoin.bip32_ckd(wallet, 0)
        bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0)
        identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv)
        bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
        identity_pub = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(bip32_identity_pub), 'hex')

        self.pubkey = identity_pub
        self.secret = identity_priv

        # Generate SIN
        sha_hash = hashlib.sha256()
        sha_hash.update(self.pubkey)
        ripe_hash = hashlib.new('ripemd160')
        ripe_hash.update(sha_hash.digest())

        self.guid = ripe_hash.hexdigest()
        self.sin = obelisk.EncodeBase58Check('\x0F\x02%s' % ripe_hash.digest())

        newsettings = {
            "secret": self.secret,
            "pubkey": self.pubkey,
            "guid": self.guid,
            "sin": self.sin,
            "bip32_seed": seed
        }
        self.db_connection.update_entries("settings", newsettings, {"market_id": self.market_id})
        self.settings.update(newsettings)
Exemple #39
0
def showDetails(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase

    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))
    print 'Seed:\t\t\t\t', seed

    priv = bitcoin.bip32_master_key(unhexlify(seed))
    print 'Xpriv:\t\t\t\t', priv

    key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv),
                                 'wif_compressed')
    print 'Key:\t\t\t\t', key

    pub = bitcoin.bip32_privtopub(priv)
    print 'Derived public key:\t', pub
    pubHex = bitcoin.bip32_extract_key(pub)
    print 'public key (hex):\t', pubHex
    print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex)

    print ""
    print "TREZOR Keys:"

    account = 0
    derivedPrivateKey = bitcoin.bip32_ckd(
        bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED), HARDENED),
        HARDENED + account)
    print 'Derived private key:', derivedPrivateKey

    privateKey = bitcoin.encode_privkey(
        bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed')
    print 'private key (wif):\t', privateKey

    derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey)
    print 'Derived public key:', derivedPublicKey

    publicKeyHex = bitcoin.privtopub(privateKey)
    print 'public key (hex):\t', publicKeyHex

    address = bitcoin.pubtoaddr(publicKeyHex)
    print 'address:\t\t\t', address

    print ""
    print "Account public keys (XPUB)"
    xpubs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(
            bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED),
                              HARDENED), HARDENED + i)
        xpub = bitcoin.bip32_privtopub(derivedPrivateKey)
        print 'Account', i, 'xpub:', xpub
        xpubs.append(xpub)

    return xpubs
    def save_settings( self ):
        #no settings to save if there is no master key
        if self.settingsStore['bip32master'] is None:
            self.changed= False
            return

        account = self.settingsWindow.accountKeyButton.get_value_as_int()
        self.settingsStore["accountNumber"] = account

        #if there is no info for this account, we have to derive the master key for it
        if( account not in self.settingsStore['accounts'] ):
            self.settingsStore['accounts'][account] = {}
            accountHardenedKey = bitcoin.bip32_ckd( self.settingsStore['bip32master'], ( account + 2**31 ) )
            #we always work with the 'external' chain, since we don't support multiple chains in an account
            accountKey = bitcoin.bip32_ckd( accountHardenedKey, 0 )
            self.settingsStore['accounts'][account]['accountKey'] = accountKey
        
        #update the number of keys
        numKeys = self.settingsWindow.numKeysEntry.get_value_as_int()
        self.settingsStore['accounts'][account]['numKeys'] = numKeys
        Settings.Instance().save_config_file( self.settingsStore )

        self.changed = False
        return
Exemple #41
0
	def __init__(self, seedarg, max_mix_depth, gaplimit=6, extend_mixdepth=False):
		super(Wallet, self).__init__()
		self.max_mix_depth = max_mix_depth
		self.seed = self.get_seed(seedarg)
		if extend_mixdepth and len(self.index_cache) > max_mix_depth:
			self.max_mix_depth = len(self.index_cache)
		self.gaplimit = gaplimit
		master = btc.bip32_master_key(self.seed)
		m_0 = btc.bip32_ckd(master, 0)
		mixing_depth_keys = [btc.bip32_ckd(m_0, c) for c in range(self.max_mix_depth)]
		self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in mixing_depth_keys]

		#self.index = [[0, 0]]*max_mix_depth
		self.index = []
		for i in range(self.max_mix_depth):
			self.index.append([0, 0])

		#example
		#index = self.index[mixing_depth]
		#key = btc.bip32_ckd(self.keys[mixing_depth][index[0]], index[1])

		self.addr_cache = {}
		self.unspent = {}
		self.spent_utxos = []
def showDetails(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase


    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))
    print 'Seed:\t\t\t\t', seed

    priv = bitcoin.bip32_master_key(unhexlify(seed))
    print 'Xpriv:\t\t\t\t', priv

    key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv), 'wif_compressed')
    print 'Key:\t\t\t\t', key


    pub = bitcoin.bip32_privtopub(priv)
    print 'Derived public key:\t', pub
    pubHex = bitcoin.bip32_extract_key(pub)
    print 'public key (hex):\t', pubHex
    print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex)


    print ""
    print "TREZOR Keys:"

    account = 0
    derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account)
    print 'Derived private key:', derivedPrivateKey

    privateKey = bitcoin.encode_privkey(bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed')
    print 'private key (wif):\t', privateKey


    derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey)
    print 'Derived public key:', derivedPublicKey

    publicKeyHex = bitcoin.privtopub(privateKey)
    print 'public key (hex):\t', publicKeyHex

    address = bitcoin.pubtoaddr(publicKeyHex)
    print 'address:\t\t\t', address

    print ""
    print "Account public keys (XPUB)"
    xpubs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+i)
        xpub = bitcoin.bip32_privtopub(derivedPrivateKey)
        print 'Account', i, 'xpub:', xpub
        xpubs.append(xpub)

    return xpubs
Exemple #43
0
def test_bip32_vector(vector):
    master = btc.bip32_master_key(vector['seed'])
    assert master == vector['keys'][0][0], 'failed: master xpriv'
    masterpub = btc.bip32_privtopub(master)
    assert masterpub == vector['keys'][0][1], 'failed: master xpub'
    currentkey = master
    for i in range(1, len(vector['depths'])):
        currentkey = btc.bip32_ckd(currentkey, vector['depths'][i])
        print currentkey
        print vector['keys'][i][0]
        assert currentkey == vector['keys'][i][
            0], 'failed: child priv key, should be: ' + vector['keys'][i][0]
        pub = btc.bip32_privtopub(currentkey)
        print pub
        print vector['keys'][i][1]
        assert pub == vector['keys'][i][
            1], 'failed: child pub key, should be: ' + vector['keys'][i][1]
Exemple #44
0
    def do_cosign(self, args):
        if not self.seed:
            raise Exception("cosign: Load or generate a seed first")

        if not self.recovery_package:
            raise Exception("cosign: Load a recovery package first (load_recovery)")

        path = None
        if args and len(args.split()) > 0:
            path = args.split()[0]

        master_xpriv = self.seed.as_HD_root()

        if path:
            path = [2**31 + int(child[:-1]) if child[-1:] in "hp'HP" else int(child) for child in path.split('/')]
            for p in path:
                master_xpriv = bitcoin.bip32_ckd(master_xpriv, p)

        self.recovery_package = recovery.cosign(master_xpriv, self.recovery_package)
Exemple #45
0
 def get_scriptpubkeys(self, change, from_index, count):
     result = []
     for index in range(from_index, from_index + count):
         pubkeys = [
             btc.bip32_extract_key(btc.bip32_ckd(branch[change], index))
             for branch in self.pubkey_branches
         ]
         pubkeys = sorted(pubkeys)
         redeemScript = ""
         redeemScript += "%x" % (0x50 + self.m)  #op_m
         for p in pubkeys:
             redeemScript += "21"  #length
             redeemScript += p
         redeemScript += "%x" % (0x50 + len(pubkeys))  #op_n
         redeemScript += "ae"  # op_checkmultisig
         scriptpubkey = self.redeem_script_to_scriptpubkey(redeemScript)
         self.scriptpubkey_index[scriptpubkey] = (change, index)
         result.append(scriptpubkey)
     self.next_index[change] = max(self.next_index[change],
                                   from_index + count)
     return result
Exemple #46
0
	def get_key(self, mixing_depth, forchange, i):
		return btc.bip32_extract_key(btc.bip32_ckd(self.keys[mixing_depth][forchange], i))
Exemple #47
0
 def _derive_address(self, change_or_deposit, index, master_key):
     xpriv = bip32_ckd(bip32_ckd(self.get_bip44_master(
         master_key), change_or_deposit), index)
     priv = bip32_extract_key(xpriv)
     address = privtoaddr(priv, self.get_address_byte())
     return address, priv
Exemple #48
0
import bitcoin
from bitcoin.deterministic import bip32_harden as h

mnemonic='saddle observe obtain scare burger nerve electric alone minute east walnut motor omit coyote time'
seed=bitcoin.mnemonic_to_seed(mnemonic)
mpriv=bitcoin.bip32_master_key(seed)

accountroot=mpriv
accountroot=bitcoin.bip32_ckd(accountroot,h(44))
accountroot=bitcoin.bip32_ckd(accountroot,h(0))
accountroot=bitcoin.bip32_ckd(accountroot,h(0))

for i in range(19):
	dkey=bitcoin.bip32_descend(accountroot,0,i)
	print(bitcoin.privtoaddr(dkey))
Exemple #49
0
def child(x, i):
    # See https://github.com/vbuterin/pybitcointools/issues/58
    return btc.bip32_ckd(x, 2**31 + i)
Exemple #50
0
def bip32_child(key, path):
    path = [2**31 + int(child[:-1]) if child[-1:] in "hp'HP" else int(child) for child in path.split('/')]
    for p in path:
        key = bitcoin.bip32_ckd(key, p)
    return key
Exemple #51
0
def load_wallet(wallet_file, get_password_fn):
    """load and if necessary decrypt a bitcoinj wallet file

    :param wallet_file: an open bitcoinj wallet file
    :type wallet_file: file
    :param get_password_fn: a callback returning a password that's called iff one is required
    :type get_password_fn: function
    :return: the Wallet protobuf message or None if no password was entered when required
    :rtype: wallet_pb2.Wallet
    """

    wallet_file.seek(0)
    magic_bytes = wallet_file.read(12)
    
    wallet_file.seek(0, os.SEEK_END)
    wallet_size = wallet_file.tell()
    wallet_file.seek(0)

    if magic_bytes[2:6] != b"org." and wallet_size % 16 == 0:
        import pylibscrypt
        takes_long = not pylibscrypt._done  # if a binary library wasn't found, this'll take a while

        ciphertext = wallet_file.read()
        assert len(ciphertext) % 16 == 0

        password = get_password_fn(takes_long)
        if not password:
            return None

        # Derive the encryption key
        salt = '\x35\x51\x03\x80\x75\xa3\xb0\xc5'
        key  = pylibscrypt.scrypt(password.encode('utf_16_be'), salt, olen=32)

        # Decrypt the wallet ( v0.5.0+ )
        try:
            plaintext = aes256_cbc_decrypt(ciphertext[16:], key, ciphertext[:16])
            if plaintext[2:6] != b"org.":
                raise ValueError('incorrect password')
        except ValueError as e:
            if e.args[0] == 'incorrect password':

                # Decrypt the wallet ( < v0.5.0 )
                iv = '\xa3\x44\x39\x1f\x53\x83\x11\xb3\x29\x54\x86\x16\xc4\x89\x72\x3e'
                plaintext = aes256_cbc_decrypt(ciphertext, key, iv)

        global multibit_hd_password
        multibit_hd_password = password

    # Else it's not whole-file encrypted
    else:
        password  = None
        plaintext = wallet_file.read()

    # Parse the wallet protobuf
    pb_wallet = wallet_pb2.Wallet()
    try:
        pb_wallet.ParseFromString(plaintext)
    except Exception as e:
        msg = 'not a wallet file: ' + str(e)
        if password:
            msg = "incorrect password (or " + msg + ")"
        raise ValueError(msg)
    
    f = open('parsed_wallet.txt','w')
    f.write(pb_wallet.__str__())
    f.close()
    
    foundAddr = []
    
    for trans in pb_wallet.transaction:
      if trans.pool == 4:
        print("--------------------------------------------------------------------------------")
        print("TXID: " + binascii.hexlify(trans.hash))
        for out in trans.transaction_output:
          print("")
          faddr = bitcoin.bin_to_b58check(bitcoin.deserialize_script(out.script_bytes)[2])
          print("Addr: " + faddr)
          foundAddr.append(faddr)
          print("Amt: " + str(out.value * 0.00000001) + " BTC")
        print("")
        print("--------------------------------------------------------------------------------")
    
    seed = None
    
    sys.stdout.write('Finding Seed....')
    
    salt = pb_wallet.encryption_parameters.salt
    dkey = pylibscrypt.scrypt(password.encode('utf_16_be'), salt, olen=32)
    
    for wkey in pb_wallet.key:
      if wkey.type == 3:
        seed = aes256_cbc_decrypt(wkey.encrypted_deterministic_seed.encrypted_private_key, dkey, wkey.encrypted_deterministic_seed.initialisation_vector)
        break
        
    if not seed:
      print("No DETERMINISTIC_MNEMONIC seed found!")
      return None
    else:
      print("Done!")
    xprv = bitcoin.bip32_master_key(seed)
    
    xprvReceive = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),0) #m/0'/0
    xprvChange = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),1) #m/0'/1
    
    rcvAddr = []
    chgAddr = []
    rcvPrivKey = []
    chgPrivKey = []
    
    sys.stdout.write("Generating Addresses/Keys.")
    for x in range(0,1000):
      if x % 10 == 0:
        sys.stdout.write(".")
      childprivReceive = bitcoin.bip32_ckd(xprvReceive, x)
      childprivChange = bitcoin.bip32_ckd(xprvChange, x)
      
      pkeyReceive = bitcoin.bip32_extract_key(childprivReceive)
      pkeyChange = bitcoin.bip32_extract_key(childprivChange)
      
      #addressReceive = privtoaddr(pkeyReceive)
      #addressChange = privtoaddr(pkeyChange)
      rcvAddr.append(bitcoin.privtoaddr(pkeyReceive))
      chgAddr.append(bitcoin.privtoaddr(pkeyChange))
      
      rcvPrivKey.append(bitcoin.encode_privkey(pkeyReceive, 'wif_compressed'))
      chgPrivKey.append(bitcoin.encode_privkey(pkeyChange, 'wif_compressed'))
    print("Done!")  
    
    print("--------------------------------------------------------------------------------")
    
    for addy in foundAddr:
      if addy in rcvAddr:
        print("")
        print("Found Address: " + addy)
        print("PrivateKey: " + rcvPrivKey[rcvAddr.index(addy)])
      elif addy in chgAddr:
        print("")
        print("Found Change Address: " + addy)
        print("PrivateKey: " + chgPrivKey[chgAddr.index(addy)])
      else:
        print("")
        print("Address not found: " + addy)
    
    print("")
    print("--------------------------------------------------------------------------------")
      
    return pb_wallet
Exemple #52
0
 def get_bip44_master(self, master_key):
     return bip32_ckd(bip32_ckd(master_key.xpriv, 44), self.currency)