From db501aa976259385fb0f2fa03bebbb16e7414b09 Mon Sep 17 00:00:00 2001 From: ThomasV Date: Thu, 1 Aug 2013 20:08:56 +0200 Subject: [PATCH 01/11] bip32 --- gui/gui_classic.py | 18 +++- lib/account.py | 234 +++++++++++++++++++++++++++++++++++++++++++ lib/bitcoin.py | 200 ++++++------------------------------ lib/simple_config.py | 2 +- lib/wallet.py | 182 +++++++++++++++++++++++---------- 5 files changed, 412 insertions(+), 224 deletions(-) create mode 100644 lib/account.py diff --git a/gui/gui_classic.py b/gui/gui_classic.py index 389911800..b02f26bd8 100644 --- a/gui/gui_classic.py +++ b/gui/gui_classic.py @@ -401,6 +401,9 @@ class ElectrumWindow(QMainWindow): new_contact = wallet_menu.addAction(_("&New contact")) new_contact.triggered.connect(self.new_contact_dialog) + new_account = wallet_menu.addAction(_("&New account")) + new_account.triggered.connect(self.new_account_dialog) + import_menu = menubar.addMenu(_("&Import")) in_labels = import_menu.addAction(_("&Labels")) in_labels.triggered.connect(self.do_import_labels) @@ -972,6 +975,7 @@ class ElectrumWindow(QMainWindow): try: tx = self.wallet.mktx( [(to_address, amount)], password, fee, account=self.current_account) except BaseException, e: + traceback.print_exc(file=sys.stdout) self.show_message(str(e)) return @@ -1263,7 +1267,7 @@ class ElectrumWindow(QMainWindow): account_items = [] for k, account in account_items: - name = account.get('name',str(k)) + name = account.get_name() c,u = self.wallet.get_account_balance(k) account_item = QTreeWidgetItem( [ name, '', self.format_amount(c+u), ''] ) l.addTopLevelItem(account_item) @@ -1280,7 +1284,7 @@ class ElectrumWindow(QMainWindow): is_red = False gap = 0 - for address in account[is_change]: + for address in account.get_addresses(is_change): h = self.wallet.history.get(address,[]) if h == []: @@ -1424,6 +1428,16 @@ class ElectrumWindow(QMainWindow): else: QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK')) + def new_account_dialog(self): + text, ok = QInputDialog.getText(self, _('New Account'), _('Name') + ':') + name = unicode(text) + if ok: + self.wallet.create_new_account(name) + self.wallet.synchronize() + self.update_contacts_tab() + self.update_history_tab() + self.update_completions() + def show_master_public_key(self): dialog = QDialog(self) dialog.setModal(1) diff --git a/lib/account.py b/lib/account.py new file mode 100644 index 000000000..b734d1447 --- /dev/null +++ b/lib/account.py @@ -0,0 +1,234 @@ +""" +todolist: + * passwords, private keys storage + * multisig service + * compatibility with old addresses for restore + * gui + + an account may use one or several MPKs. + due to the type 1 derivations, we need to pass the mpk to this function + None : all accounts + -1 : imported + 0,1... : seeded sequences + + each account has a public and private master key +""" + +from bitcoin import * + + +class Account(object): + def __init__(self, v): + self.addresses = v.get('0', []) + self.change = v.get('1', []) + self.name = v.get('name', 'unnamed') + + def dump(self): + return {'0':self.addresses, '1':self.change, 'name':self.name} + + def get_name(self): + return self.name + + def get_addresses(self, for_change): + return self.change[:] if for_change else self.addresses[:] + + def create_new_address(self, for_change): + addresses = self.change if for_change else self.addresses + n = len(addresses) + address = self.get_new_address( for_change, n) + addresses.append(address) + print address + return address + + def get_new_address(self, for_change, n): + pass + + + + +class OldAccount(Account): + """ Privatekey(type,n) = Master_private_key + H(n|S|type) """ + + def __init__(self, mpk, mpk2 = None, mpk3 = None): + self.mpk = mpk + self.mpk2 = mpk2 + self.mpk3 = mpk3 + + @classmethod + def mpk_from_seed(klass, seed): + curve = SECP256k1 + secexp = klass.stretch_key(seed) + master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) + master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') + return master_public_key + + @classmethod + def stretch_key(self,seed): + oldseed = seed + for i in range(100000): + seed = hashlib.sha256(seed + oldseed).digest() + return string_to_number( seed ) + + def get_sequence(self, sequence, mpk): + for_change, n = sequence + return string_to_number( Hash( "%d:%d:"%(n,for_change) + mpk.decode('hex') ) ) + + def get_address(self, sequence): + if not self.mpk2: + pubkey = self.get_pubkey(sequence) + address = public_key_to_bc_address( pubkey.decode('hex') ) + elif not self.mpk3: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) + address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"] + else: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) + pubkey3 = self.get_pubkey(sequence, mpk = self.mpk3) + address = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)["address"] + return address + + def get_pubkey(self, sequence, mpk=None): + curve = SECP256k1 + if mpk is None: mpk = self.mpk + z = self.get_sequence(sequence, mpk) + master_public_key = ecdsa.VerifyingKey.from_string( mpk.decode('hex'), curve = SECP256k1 ) + pubkey_point = master_public_key.pubkey.point + z*curve.generator + public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 ) + return '04' + public_key2.to_string().encode('hex') + + def get_private_key_from_stretched_exponent(self, sequence, secexp): + order = generator_secp256k1.order() + secexp = ( secexp + self.get_sequence(sequence, self.mpk) ) % order + pk = number_to_string( secexp, generator_secp256k1.order() ) + compressed = False + return SecretToASecret( pk, compressed ) + + def get_private_key(self, sequence, seed): + secexp = self.stretch_key(seed) + return self.get_private_key_from_stretched_exponent(sequence, secexp) + + def get_private_keys(self, sequence_list, seed): + secexp = self.stretch_key(seed) + return [ self.get_private_key_from_stretched_exponent( sequence, secexp) for sequence in sequence_list] + + def check_seed(self, seed): + curve = SECP256k1 + secexp = self.stretch_key(seed) + master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) + master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') + if master_public_key != self.mpk: + print_error('invalid password (mpk)') + raise BaseException('Invalid password') + return True + + def get_input_info(self, sequence): + if not self.mpk2: + pk_addr = self.get_address(sequence) + redeemScript = None + elif not self.mpk3: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence,mpk=self.mpk2) + pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key + redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript'] + else: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) + pubkey3 = self.get_pubkey(sequence, mpk=self.mpk3) + pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key + redeemScript = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)['redeemScript'] + return pk_addr, redeemScript + + + +class BIP32_Account(Account): + + def __init__(self, v): + Account.__init__(self, v) + self.c = v['c'].decode('hex') + self.K = v['K'].decode('hex') + self.cK = v['cK'].decode('hex') + + def dump(self): + d = Account.dump(self) + d['c'] = self.c.encode('hex') + d['K'] = self.K.encode('hex') + d['cK'] = self.cK.encode('hex') + return d + + def get_new_address(self, for_change, n): + pubkey = self.get_pubkey(for_change, n) + address = public_key_to_bc_address( pubkey ) + return address + + def get_pubkey(self, for_change, n): + K = self.K + chain = self.c + for i in [for_change, n]: + K, K_compressed, chain = CKD_prime(K, chain, i) + return K_compressed + + def get_address(self, sequence): + for_change, n = sequence + pubkey = self.get_pubkey(for_change, n) + address = public_key_to_bc_address( pubkey ) + return address + + def get_private_key(self, sequence, master_k): + chain = self.c + k = master_k + for i in sequence: + k, chain = CKD(k, chain, i) + return SecretToASecret(k, True) + + def get_private_keys(self, sequence_list, seed): + return [ self.get_private_key( sequence, seed) for sequence in sequence_list] + + def check_seed(self, seed): + master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) + assert self.mpk == (master_public_key.encode('hex'), master_chain.encode('hex')) + + def get_input_info(self, sequence): + pk_addr = self.get_address(sequence) + redeemScript = None + return pk_addr, redeemScript + + + +class BIP32_Account_2of2(BIP32_Account): + + def __init__(self, v): + BIP32_Account.__init__(self, v) + self.c2 = v['c2'].decode('hex') + self.K2 = v['K2'].decode('hex') + self.cK2 = v['cK2'].decode('hex') + + def dump(self): + d = BIP32_Account.dump(self) + d['c2'] = self.c2.encode('hex') + d['K2'] = self.K2.encode('hex') + d['cK2'] = self.cK2.encode('hex') + return d + + def get_pubkey2(self, for_change, n): + K = self.K2 + chain = self.c2 + for i in [for_change, n]: + K, K_compressed, chain = CKD_prime(K, chain, i) + return K_compressed + + def get_new_address(self, for_change, n): + pubkey1 = self.get_pubkey(for_change, n) + pubkey2 = self.get_pubkey2(for_change, n) + address = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)["address"] + return address + + def get_input_info(self, sequence): + chain, i = sequence + pubkey1 = self.get_pubkey(chain, i) + pubkey2 = self.get_pubkey2(chain, i) + # fixme + pk_addr = None # public_key_to_bc_address( pubkey1 ) # we need to return that address to get the right private key + redeemScript = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)['redeemScript'] + return pk_addr, redeemScript + diff --git a/lib/bitcoin.py b/lib/bitcoin.py index 61d0bd0cb..b068baaff 100644 --- a/lib/bitcoin.py +++ b/lib/bitcoin.py @@ -427,169 +427,29 @@ def CKD_prime(K, c, n): -class ElectrumSequence: - """ Privatekey(type,n) = Master_private_key + H(n|S|type) """ - - def __init__(self, mpk, mpk2 = None, mpk3 = None): - self.mpk = mpk - self.mpk2 = mpk2 - self.mpk3 = mpk3 +def bip32_private_derivation(k, c, branch, sequence): + assert sequence.startswith(branch) + sequence = sequence[len(branch):] + for n in sequence.split('/'): + if n == '': continue + n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n) + k, c = CKD(k, c, n) + K, K_compressed = get_pubkeys_from_secret(k) + return k.encode('hex'), c.encode('hex'), K.encode('hex'), K_compressed.encode('hex') - @classmethod - def mpk_from_seed(klass, seed): - curve = SECP256k1 - secexp = klass.stretch_key(seed) - master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) - master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') - return master_public_key - @classmethod - def stretch_key(self,seed): - oldseed = seed - for i in range(100000): - seed = hashlib.sha256(seed + oldseed).digest() - return string_to_number( seed ) - - def get_sequence(self, sequence, mpk): - for_change, n = sequence - return string_to_number( Hash( "%d:%d:"%(n,for_change) + mpk.decode('hex') ) ) - - def get_address(self, sequence): - if not self.mpk2: - pubkey = self.get_pubkey(sequence) - address = public_key_to_bc_address( pubkey.decode('hex') ) - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk = self.mpk3) - address = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)["address"] - return address - - def get_pubkey(self, sequence, mpk=None): - curve = SECP256k1 - if mpk is None: mpk = self.mpk - z = self.get_sequence(sequence, mpk) - master_public_key = ecdsa.VerifyingKey.from_string( mpk.decode('hex'), curve = SECP256k1 ) - pubkey_point = master_public_key.pubkey.point + z*curve.generator - public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 ) - return '04' + public_key2.to_string().encode('hex') - - def get_private_key_from_stretched_exponent(self, sequence, secexp): - order = generator_secp256k1.order() - secexp = ( secexp + self.get_sequence(sequence, self.mpk) ) % order - pk = number_to_string( secexp, generator_secp256k1.order() ) - compressed = False - return SecretToASecret( pk, compressed ) - - def get_private_key(self, sequence, seed): - secexp = self.stretch_key(seed) - return self.get_private_key_from_stretched_exponent(sequence, secexp) - - def get_private_keys(self, sequence_list, seed): - secexp = self.stretch_key(seed) - return [ self.get_private_key_from_stretched_exponent( sequence, secexp) for sequence in sequence_list] - - def check_seed(self, seed): - curve = SECP256k1 - secexp = self.stretch_key(seed) - master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) - master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') - if master_public_key != self.mpk: - print_error('invalid password (mpk)') - raise BaseException('Invalid password') - return True - - def get_input_info(self, sequence): - if not self.mpk2: - pk_addr = self.get_address(sequence) - redeemScript = None - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence,mpk=self.mpk2) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript'] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk=self.mpk3) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)['redeemScript'] - return pk_addr, redeemScript +def bip32_public_derivation(c, K, branch, sequence): + assert sequence.startswith(branch) + sequence = sequence[len(branch):] + for n in sequence.split('/'): + n = int(n) + K, cK, c = CKD_prime(K, c, n) + return c.encode('hex'), K.encode('hex'), cK.encode('hex') -class BIP32Sequence: - def __init__(self, mpk, mpk2 = None, mpk3 = None): - self.mpk = mpk - self.mpk2 = mpk2 - self.mpk3 = mpk3 - - @classmethod - def mpk_from_seed(klass, seed): - master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) - return master_public_key.encode('hex'), master_chain.encode('hex') - - def get_pubkey(self, sequence, mpk = None): - if not mpk: mpk = self.mpk - master_public_key, master_chain = mpk - K = master_public_key.decode('hex') - chain = master_chain.decode('hex') - for i in sequence: - K, K_compressed, chain = CKD_prime(K, chain, i) - return K_compressed.encode('hex') - - def get_address(self, sequence): - if not self.mpk2: - pubkey = self.get_pubkey(sequence) - address = public_key_to_bc_address( pubkey.decode('hex') ) - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk = self.mpk3) - address = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)["address"] - return address - - def get_private_key(self, sequence, seed): - master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) - chain = master_chain - k = master_secret - for i in sequence: - k, chain = CKD(k, chain, i) - return SecretToASecret(k, True) - - def get_private_keys(self, sequence_list, seed): - return [ self.get_private_key( sequence, seed) for sequence in sequence_list] - - def check_seed(self, seed): - master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) - assert self.mpk == (master_public_key.encode('hex'), master_chain.encode('hex')) - - def get_input_info(self, sequence): - if not self.mpk2: - pk_addr = self.get_address(sequence) - redeemScript = None - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript'] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk=self.mpk3) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)['redeemScript'] - return pk_addr, redeemScript ################################## transactions @@ -734,9 +594,10 @@ class Transaction: txin = self.inputs[i] tx_for_sig = self.serialize( self.inputs, self.outputs, for_sig = i ) - if txin.get('redeemScript'): + redeem_script = txin.get('redeemScript') + if redeem_script: # 1 parse the redeem script - num, redeem_pubkeys = deserialize.parse_redeemScript(txin.get('redeemScript')) + num, redeem_pubkeys = deserialize.parse_redeemScript(redeem_script) self.inputs[i]["pubkeys"] = redeem_pubkeys # build list of public/private keys @@ -747,19 +608,25 @@ class Transaction: pubkey = GetPubKey(pkey.pubkey, compressed) keypairs[ pubkey.encode('hex') ] = sec + print "keypairs", keypairs + print redeem_script, redeem_pubkeys + # list of already existing signatures signatures = txin.get("signatures",[]) print_error("signatures",signatures) for pubkey in redeem_pubkeys: - public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1) - for s in signatures: - try: - public_key.verify_digest( s.decode('hex')[:-1], Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der) - break - except ecdsa.keys.BadSignatureError: - continue - else: + + # here we have compressed key.. it won't work + #public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1) + #for s in signatures: + # try: + # public_key.verify_digest( s.decode('hex')[:-1], Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der) + # break + # except ecdsa.keys.BadSignatureError: + # continue + #else: + if 1: # check if we have a key corresponding to the redeem script if pubkey in keypairs.keys(): # add signature @@ -783,7 +650,6 @@ class Transaction: compressed = is_compressed(sec) pkey = regenerate_key(sec) secexp = pkey.secret - private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) public_key = private_key.get_verifying_key() pkey = EC_KEY(secexp) diff --git a/lib/simple_config.py b/lib/simple_config.py index bff785184..f8a9e00e9 100644 --- a/lib/simple_config.py +++ b/lib/simple_config.py @@ -206,7 +206,7 @@ a SimpleConfig instance then reads the wallet file. def save_wallet_config(self): # prevent the creation of incomplete wallets - if self.wallet_config.get('master_public_key') is None: + if self.wallet_config.get('master_public_keys') is None: return s = repr(self.wallet_config) diff --git a/lib/wallet.py b/lib/wallet.py index 1957d885e..0bc757ee4 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -32,7 +32,7 @@ import time from util import print_msg, print_error, user_dir, format_satoshis from bitcoin import * - +from account import * # AES encryption EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s)) @@ -85,14 +85,12 @@ class Wallet: self.imported_keys = config.get('imported_keys',{}) self.history = config.get('addr_history',{}) # address -> list(txid, height) - self.accounts = config.get('accounts', {}) # this should not include public keys - self.SequenceClass = ElectrumSequence - self.sequences = {} - self.sequences[0] = self.SequenceClass(self.config.get('master_public_key')) - if self.accounts.get(0) is None: - self.accounts[0] = { 0:[], 1:[], 'name':'Main account' } + self.master_public_keys = config.get('master_public_keys',{}) + self.master_private_keys = config.get('master_private_keys', {}) + + self.load_accounts(config) self.transactions = {} tx = config.get('transactions',{}) @@ -167,18 +165,88 @@ class Wallet: seed = random_seed(128) self.seed = seed + def save_seed(self): self.config.set_key('seed', self.seed, True) self.config.set_key('seed_version', self.seed_version, True) - mpk = self.SequenceClass.mpk_from_seed(self.seed) - self.init_sequence(mpk) + + master_k, master_c, master_K, master_cK = bip32_init(self.seed) + + k0, c0, K0, cK0 = bip32_private_derivation(master_k, master_c, "m/", "m/0'/") + k1, c1, K1, cK1 = bip32_private_derivation(master_k, master_c, "m/", "m/1'/") + k2, c2, K2, cK2 = bip32_private_derivation(master_k, master_c, "m/", "m/2'/") + + self.master_public_keys = { + "m/0'/": (c0, K0, cK0), + "m/1'/": (c1, K1, cK1), + "m/2'/": (c2, K2, cK2) + } + + self.master_private_keys = { + "m/0'/": k0, + "m/1'/": k1 + } + # send k2 to service + + self.config.set_key('master_public_keys', self.master_public_keys, True) + self.config.set_key('master_private_keys', self.master_private_keys, True) + + # create default account + self.create_new_account('Main account') + + + def create_new_account(self, name): + keys = self.accounts.keys() + i = 0 + + while True: + derivation = "m/0'/%d'"%i + if derivation not in keys: break + i += 1 + + start = "m/0'/" + master_c, master_K, master_cK = self.master_public_keys[start] + master_k = self.master_private_keys[start] # needs decryption + k, c, K, cK = bip32_private_derivation(master_k, master_c, start, derivation) # this is a type 1 derivation + + self.accounts[derivation] = BIP32_Account({ 'name':name, 'c':c, 'K':K, 'cK':cK }) + self.save_accounts() + + def create_p2sh_account(self, name): + keys = self.accounts.keys() + i = 0 + while True: + account_id = "m/1'/%d & m/2'/%d"%(i,i) + if account_id not in keys: break + i += 1 + + master_c1, master_K1, _ = self.master_public_keys["m/1'/"] + c1, K1, cK1 = bip32_public_derivation(master_c1.decode('hex'), master_K1.decode('hex'), "m/1'/", "m/1'/%d"%i) + + master_c2, master_K2, _ = self.master_public_keys["m/2'/"] + c2, K2, cK2 = bip32_public_derivation(master_c2.decode('hex'), master_K2.decode('hex'), "m/2'/", "m/2'/%d"%i) + + self.accounts[account_id] = BIP32_Account_2of2({ 'name':name, 'c':c1, 'K':K1, 'cK':cK1, 'c2':c2, 'K2':K2, 'cK2':cK2 }) + self.save_accounts() + + + def save_accounts(self): + d = {} + for k, v in self.accounts.items(): + d[k] = v.dump() + self.config.set_key('accounts', d, True) + + + def load_accounts(self, config): + d = config.get('accounts', {}) + self.accounts = {} + for k, v in d.items(): + if '&' in k: + self.accounts[k] = BIP32_Account_2of2(v) + else: + self.accounts[k] = BIP32_Account(v) - def init_sequence(self, mpk): - self.config.set_key('master_public_key', mpk, True) - self.sequences[0] = self.SequenceClass(mpk) - self.accounts[0] = { 0:[], 1:[], 'name':'Main account' } - self.config.set_key('accounts', self.accounts, True) def addresses(self, include_change = True): @@ -198,6 +266,7 @@ class Wallet: return s[0] == 1 def get_master_public_key(self): + raise return self.config.get("master_public_key") def get_address_index(self, address): @@ -205,7 +274,7 @@ class Wallet: return -1, None for account in self.accounts.keys(): for for_change in [0,1]: - addresses = self.accounts[account][for_change] + addresses = self.accounts[account].get_addresses(for_change) for addr in addresses: if address == addr: return account, (for_change, addresses.index(addr)) @@ -214,12 +283,12 @@ class Wallet: def get_public_key(self, address): account, sequence = self.get_address_index(address) - return self.sequences[account].get_pubkey( sequence ) + return self.accounts[account].get_pubkey( sequence ) def decode_seed(self, password): seed = pw_decode(self.seed, password) - self.sequences[0].check_seed(seed) + #todo: #self.sequences[0].check_seed(seed) return seed def get_private_key(self, address, password): @@ -230,19 +299,27 @@ class Wallet: # decode seed in any case, in order to test the password seed = self.decode_seed(password) out = {} - l_sequences = [] - l_addresses = [] for address in addresses: if address in self.imported_keys.keys(): out[address] = pw_decode( self.imported_keys[address], password ) else: account, sequence = self.get_address_index(address) - if account == 0: - l_sequences.append(sequence) - l_addresses.append(address) + print "found index", address, account, sequence + if account == "m/0'/0'": + # FIXME: this is ugly + master_k = self.master_private_keys["m/0'/"] + master_c, _, _ = self.master_public_keys["m/0'/"] + master_k, master_c = CKD(master_k, master_c, 0 + BIP32_PRIME) + pk = self.accounts["m/0'/0'"].get_private_key(sequence, master_k) + out[address] = pk + + elif account == "m/1'/1 & m/2'/1": + master_k = self.master_private_keys["m/1'/"] + master_c, master_K, _ = self.master_public_keys["m/1'/"] + master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), 1) + pk = self.accounts[account].get_private_key(sequence, master_k) + out[address] = pk - pk = self.sequences[0].get_private_keys(l_sequences, seed) - for i, address in enumerate(l_addresses): out[address] = pk[i] return out @@ -281,8 +358,8 @@ class Wallet: if txin.get('KeyID'): account, name, sequence = txin.get('KeyID') if name != 'Electrum': continue - sec = self.sequences[account].get_private_key(sequence, seed) - addr = self.sequences[account].get_address(sequence) + sec = self.accounts[account].get_private_key(sequence, seed) + addr = self.accounts[account].get_address(sequence) txin['address'] = addr private_keys[addr] = sec @@ -313,20 +390,6 @@ class Wallet: print_error("Verification error: {0}".format(e)) return False - def create_new_address(self, account, for_change): - addresses = self.accounts[account][for_change] - n = len(addresses) - address = self.get_new_address( account, for_change, n) - self.accounts[account][for_change].append(address) - self.history[address] = [] - print_msg(address) - return address - - - def get_new_address(self, account, for_change, n): - return self.sequences[account].get_address((for_change, n)) - print address - return address def change_gap_limit(self, value): if value >= self.gap_limit: @@ -345,7 +408,7 @@ class Wallet: self.gap_limit = value self.config.set_key('gap_limit', self.gap_limit, True) - self.config.set_key('accounts', self.accounts, True) + self.save_accounts() return True else: return False @@ -363,7 +426,7 @@ class Wallet: nmax = 0 for account in self.accounts.values(): - addresses = account[0] + addresses = account.get_addresses(0) k = self.num_unused_trailing_addresses(addresses) for a in addresses[0:-k]: if self.history.get(a): @@ -391,16 +454,22 @@ class Wallet: def synchronize_sequence(self, account, for_change): limit = self.gap_limit_for_change if for_change else self.gap_limit - addresses = self.accounts[account][for_change] new_addresses = [] while True: + addresses = account.get_addresses(for_change) if len(addresses) < limit: - new_addresses.append( self.create_new_address(account, for_change) ) + address = account.create_new_address(for_change) + self.history[address] = [] + new_addresses.append( address ) continue + if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]: break else: - new_addresses.append( self.create_new_address(account, for_change) ) + address = account.create_new_address(for_change) + self.history[address] = [] + new_addresses.append( address ) + return new_addresses @@ -412,10 +481,10 @@ class Wallet: def synchronize(self): new = [] - for account in self.accounts.keys(): + for account in self.accounts.values(): new += self.synchronize_account(account) if new: - self.config.set_key('accounts', self.accounts, True) + self.save_accounts() self.config.set_key('addr_history', self.history, True) return new @@ -522,7 +591,7 @@ class Wallet: def get_accounts(self): accounts = {} for k, account in self.accounts.items(): - accounts[k] = account.get('name') + accounts[k] = account.name if self.imported_keys: accounts[-1] = 'Imported keys' return accounts @@ -534,8 +603,8 @@ class Wallet: o = self.imported_keys.keys() else: ac = self.accounts[a] - o = ac[0][:] - if include_change: o += ac[1] + o = ac.get_addresses(0) + if include_change: o += ac.get_addresses(1) return o def get_imported_balance(self): @@ -818,14 +887,20 @@ class Wallet: pk_addresses.append(address) continue account, sequence = self.get_address_index(address) - txin['KeyID'] = (account, 'Electrum', sequence) # used by the server to find the key - pk_addr, redeemScript = self.sequences[account].get_input_info(sequence) + + txin['KeyID'] = (account, 'BIP32', sequence) # used by the server to find the key + + _, redeemScript = self.accounts[account].get_input_info(sequence) + if redeemScript: txin['redeemScript'] = redeemScript - pk_addresses.append(pk_addr) + pk_addresses.append(address) + + print "pk_addresses", pk_addresses # get all private keys at once. if self.seed: private_keys = self.get_private_keys(pk_addresses, password) + print "private keys", private_keys tx.sign(private_keys) for address, x in outputs: @@ -920,7 +995,6 @@ class Wallet: s = { 'use_change': self.use_change, 'fee_per_kb': self.fee, - 'accounts': self.accounts, 'addr_history': self.history, 'labels': self.labels, 'contacts': self.addressbook, From b526abdc40a099b9f9e3acc7ffa888e06f56084d Mon Sep 17 00:00:00 2001 From: thomasv Date: Sat, 3 Aug 2013 17:30:59 +0200 Subject: [PATCH 02/11] add account module --- lib/__init__.py | 1 + setup.py | 1 + 2 files changed, 2 insertions(+) diff --git a/lib/__init__.py b/lib/__init__.py index c3100ecf5..f162a9441 100644 --- a/lib/__init__.py +++ b/lib/__init__.py @@ -6,6 +6,7 @@ from verifier import WalletVerifier from interface import Interface, pick_random_server, DEFAULT_SERVERS from simple_config import SimpleConfig import bitcoin +import account from bitcoin import Transaction, EC_KEY, is_valid from mnemonic import mn_encode as mnemonic_encode from mnemonic import mn_decode as mnemonic_decode diff --git a/setup.py b/setup.py index 0ea8aa317..8952527c7 100644 --- a/setup.py +++ b/setup.py @@ -59,6 +59,7 @@ setup(name = "Electrum", 'electrum.socks', 'electrum.msqr', 'electrum.util', + 'electrum.account', 'electrum.bitcoin', 'electrum.deserialize', 'electrum.verifier', From 799c2e89844b0d78a482f2b88eccab9be05bc840 Mon Sep 17 00:00:00 2001 From: thomasv Date: Sun, 4 Aug 2013 16:46:47 +0200 Subject: [PATCH 03/11] get_new_address -> get_address --- lib/account.py | 17 ++++++----------- lib/wallet.py | 4 ++-- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/lib/account.py b/lib/account.py index b734d1447..85a3471f3 100644 --- a/lib/account.py +++ b/lib/account.py @@ -35,12 +35,12 @@ class Account(object): def create_new_address(self, for_change): addresses = self.change if for_change else self.addresses n = len(addresses) - address = self.get_new_address( for_change, n) + address = self.get_address( for_change, n) addresses.append(address) print address return address - def get_new_address(self, for_change, n): + def get_address(self, for_change, n): pass @@ -156,7 +156,7 @@ class BIP32_Account(Account): d['cK'] = self.cK.encode('hex') return d - def get_new_address(self, for_change, n): + def get_address(self, for_change, n): pubkey = self.get_pubkey(for_change, n) address = public_key_to_bc_address( pubkey ) return address @@ -168,12 +168,6 @@ class BIP32_Account(Account): K, K_compressed, chain = CKD_prime(K, chain, i) return K_compressed - def get_address(self, sequence): - for_change, n = sequence - pubkey = self.get_pubkey(for_change, n) - address = public_key_to_bc_address( pubkey ) - return address - def get_private_key(self, sequence, master_k): chain = self.c k = master_k @@ -189,7 +183,8 @@ class BIP32_Account(Account): assert self.mpk == (master_public_key.encode('hex'), master_chain.encode('hex')) def get_input_info(self, sequence): - pk_addr = self.get_address(sequence) + chain, i = sequence + pk_addr = self.get_address(chain, i) redeemScript = None return pk_addr, redeemScript @@ -217,7 +212,7 @@ class BIP32_Account_2of2(BIP32_Account): K, K_compressed, chain = CKD_prime(K, chain, i) return K_compressed - def get_new_address(self, for_change, n): + def get_address(self, for_change, n): pubkey1 = self.get_pubkey(for_change, n) pubkey2 = self.get_pubkey2(for_change, n) address = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)["address"] diff --git a/lib/wallet.py b/lib/wallet.py index 0bc757ee4..d5da6b31a 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -313,10 +313,10 @@ class Wallet: pk = self.accounts["m/0'/0'"].get_private_key(sequence, master_k) out[address] = pk - elif account == "m/1'/1 & m/2'/1": + elif account == "m/1'/0 & m/2'/0": master_k = self.master_private_keys["m/1'/"] master_c, master_K, _ = self.master_public_keys["m/1'/"] - master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), 1) + master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), 0) pk = self.accounts[account].get_private_key(sequence, master_k) out[address] = pk From f4207d7e4c0214490371adc835540ffd4b42456d Mon Sep 17 00:00:00 2001 From: ThomasV Date: Thu, 1 Aug 2013 20:08:56 +0200 Subject: [PATCH 04/11] bip32 --- gui/gui_classic.py | 18 +++- lib/account.py | 234 +++++++++++++++++++++++++++++++++++++++++++ lib/bitcoin.py | 200 ++++++------------------------------ lib/simple_config.py | 2 +- lib/wallet.py | 182 +++++++++++++++++++++++---------- 5 files changed, 412 insertions(+), 224 deletions(-) create mode 100644 lib/account.py diff --git a/gui/gui_classic.py b/gui/gui_classic.py index 389911800..b02f26bd8 100644 --- a/gui/gui_classic.py +++ b/gui/gui_classic.py @@ -401,6 +401,9 @@ class ElectrumWindow(QMainWindow): new_contact = wallet_menu.addAction(_("&New contact")) new_contact.triggered.connect(self.new_contact_dialog) + new_account = wallet_menu.addAction(_("&New account")) + new_account.triggered.connect(self.new_account_dialog) + import_menu = menubar.addMenu(_("&Import")) in_labels = import_menu.addAction(_("&Labels")) in_labels.triggered.connect(self.do_import_labels) @@ -972,6 +975,7 @@ class ElectrumWindow(QMainWindow): try: tx = self.wallet.mktx( [(to_address, amount)], password, fee, account=self.current_account) except BaseException, e: + traceback.print_exc(file=sys.stdout) self.show_message(str(e)) return @@ -1263,7 +1267,7 @@ class ElectrumWindow(QMainWindow): account_items = [] for k, account in account_items: - name = account.get('name',str(k)) + name = account.get_name() c,u = self.wallet.get_account_balance(k) account_item = QTreeWidgetItem( [ name, '', self.format_amount(c+u), ''] ) l.addTopLevelItem(account_item) @@ -1280,7 +1284,7 @@ class ElectrumWindow(QMainWindow): is_red = False gap = 0 - for address in account[is_change]: + for address in account.get_addresses(is_change): h = self.wallet.history.get(address,[]) if h == []: @@ -1424,6 +1428,16 @@ class ElectrumWindow(QMainWindow): else: QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK')) + def new_account_dialog(self): + text, ok = QInputDialog.getText(self, _('New Account'), _('Name') + ':') + name = unicode(text) + if ok: + self.wallet.create_new_account(name) + self.wallet.synchronize() + self.update_contacts_tab() + self.update_history_tab() + self.update_completions() + def show_master_public_key(self): dialog = QDialog(self) dialog.setModal(1) diff --git a/lib/account.py b/lib/account.py new file mode 100644 index 000000000..b734d1447 --- /dev/null +++ b/lib/account.py @@ -0,0 +1,234 @@ +""" +todolist: + * passwords, private keys storage + * multisig service + * compatibility with old addresses for restore + * gui + + an account may use one or several MPKs. + due to the type 1 derivations, we need to pass the mpk to this function + None : all accounts + -1 : imported + 0,1... : seeded sequences + + each account has a public and private master key +""" + +from bitcoin import * + + +class Account(object): + def __init__(self, v): + self.addresses = v.get('0', []) + self.change = v.get('1', []) + self.name = v.get('name', 'unnamed') + + def dump(self): + return {'0':self.addresses, '1':self.change, 'name':self.name} + + def get_name(self): + return self.name + + def get_addresses(self, for_change): + return self.change[:] if for_change else self.addresses[:] + + def create_new_address(self, for_change): + addresses = self.change if for_change else self.addresses + n = len(addresses) + address = self.get_new_address( for_change, n) + addresses.append(address) + print address + return address + + def get_new_address(self, for_change, n): + pass + + + + +class OldAccount(Account): + """ Privatekey(type,n) = Master_private_key + H(n|S|type) """ + + def __init__(self, mpk, mpk2 = None, mpk3 = None): + self.mpk = mpk + self.mpk2 = mpk2 + self.mpk3 = mpk3 + + @classmethod + def mpk_from_seed(klass, seed): + curve = SECP256k1 + secexp = klass.stretch_key(seed) + master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) + master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') + return master_public_key + + @classmethod + def stretch_key(self,seed): + oldseed = seed + for i in range(100000): + seed = hashlib.sha256(seed + oldseed).digest() + return string_to_number( seed ) + + def get_sequence(self, sequence, mpk): + for_change, n = sequence + return string_to_number( Hash( "%d:%d:"%(n,for_change) + mpk.decode('hex') ) ) + + def get_address(self, sequence): + if not self.mpk2: + pubkey = self.get_pubkey(sequence) + address = public_key_to_bc_address( pubkey.decode('hex') ) + elif not self.mpk3: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) + address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"] + else: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) + pubkey3 = self.get_pubkey(sequence, mpk = self.mpk3) + address = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)["address"] + return address + + def get_pubkey(self, sequence, mpk=None): + curve = SECP256k1 + if mpk is None: mpk = self.mpk + z = self.get_sequence(sequence, mpk) + master_public_key = ecdsa.VerifyingKey.from_string( mpk.decode('hex'), curve = SECP256k1 ) + pubkey_point = master_public_key.pubkey.point + z*curve.generator + public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 ) + return '04' + public_key2.to_string().encode('hex') + + def get_private_key_from_stretched_exponent(self, sequence, secexp): + order = generator_secp256k1.order() + secexp = ( secexp + self.get_sequence(sequence, self.mpk) ) % order + pk = number_to_string( secexp, generator_secp256k1.order() ) + compressed = False + return SecretToASecret( pk, compressed ) + + def get_private_key(self, sequence, seed): + secexp = self.stretch_key(seed) + return self.get_private_key_from_stretched_exponent(sequence, secexp) + + def get_private_keys(self, sequence_list, seed): + secexp = self.stretch_key(seed) + return [ self.get_private_key_from_stretched_exponent( sequence, secexp) for sequence in sequence_list] + + def check_seed(self, seed): + curve = SECP256k1 + secexp = self.stretch_key(seed) + master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) + master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') + if master_public_key != self.mpk: + print_error('invalid password (mpk)') + raise BaseException('Invalid password') + return True + + def get_input_info(self, sequence): + if not self.mpk2: + pk_addr = self.get_address(sequence) + redeemScript = None + elif not self.mpk3: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence,mpk=self.mpk2) + pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key + redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript'] + else: + pubkey1 = self.get_pubkey(sequence) + pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) + pubkey3 = self.get_pubkey(sequence, mpk=self.mpk3) + pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key + redeemScript = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)['redeemScript'] + return pk_addr, redeemScript + + + +class BIP32_Account(Account): + + def __init__(self, v): + Account.__init__(self, v) + self.c = v['c'].decode('hex') + self.K = v['K'].decode('hex') + self.cK = v['cK'].decode('hex') + + def dump(self): + d = Account.dump(self) + d['c'] = self.c.encode('hex') + d['K'] = self.K.encode('hex') + d['cK'] = self.cK.encode('hex') + return d + + def get_new_address(self, for_change, n): + pubkey = self.get_pubkey(for_change, n) + address = public_key_to_bc_address( pubkey ) + return address + + def get_pubkey(self, for_change, n): + K = self.K + chain = self.c + for i in [for_change, n]: + K, K_compressed, chain = CKD_prime(K, chain, i) + return K_compressed + + def get_address(self, sequence): + for_change, n = sequence + pubkey = self.get_pubkey(for_change, n) + address = public_key_to_bc_address( pubkey ) + return address + + def get_private_key(self, sequence, master_k): + chain = self.c + k = master_k + for i in sequence: + k, chain = CKD(k, chain, i) + return SecretToASecret(k, True) + + def get_private_keys(self, sequence_list, seed): + return [ self.get_private_key( sequence, seed) for sequence in sequence_list] + + def check_seed(self, seed): + master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) + assert self.mpk == (master_public_key.encode('hex'), master_chain.encode('hex')) + + def get_input_info(self, sequence): + pk_addr = self.get_address(sequence) + redeemScript = None + return pk_addr, redeemScript + + + +class BIP32_Account_2of2(BIP32_Account): + + def __init__(self, v): + BIP32_Account.__init__(self, v) + self.c2 = v['c2'].decode('hex') + self.K2 = v['K2'].decode('hex') + self.cK2 = v['cK2'].decode('hex') + + def dump(self): + d = BIP32_Account.dump(self) + d['c2'] = self.c2.encode('hex') + d['K2'] = self.K2.encode('hex') + d['cK2'] = self.cK2.encode('hex') + return d + + def get_pubkey2(self, for_change, n): + K = self.K2 + chain = self.c2 + for i in [for_change, n]: + K, K_compressed, chain = CKD_prime(K, chain, i) + return K_compressed + + def get_new_address(self, for_change, n): + pubkey1 = self.get_pubkey(for_change, n) + pubkey2 = self.get_pubkey2(for_change, n) + address = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)["address"] + return address + + def get_input_info(self, sequence): + chain, i = sequence + pubkey1 = self.get_pubkey(chain, i) + pubkey2 = self.get_pubkey2(chain, i) + # fixme + pk_addr = None # public_key_to_bc_address( pubkey1 ) # we need to return that address to get the right private key + redeemScript = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)['redeemScript'] + return pk_addr, redeemScript + diff --git a/lib/bitcoin.py b/lib/bitcoin.py index 61d0bd0cb..b068baaff 100644 --- a/lib/bitcoin.py +++ b/lib/bitcoin.py @@ -427,169 +427,29 @@ def CKD_prime(K, c, n): -class ElectrumSequence: - """ Privatekey(type,n) = Master_private_key + H(n|S|type) """ - - def __init__(self, mpk, mpk2 = None, mpk3 = None): - self.mpk = mpk - self.mpk2 = mpk2 - self.mpk3 = mpk3 +def bip32_private_derivation(k, c, branch, sequence): + assert sequence.startswith(branch) + sequence = sequence[len(branch):] + for n in sequence.split('/'): + if n == '': continue + n = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n) + k, c = CKD(k, c, n) + K, K_compressed = get_pubkeys_from_secret(k) + return k.encode('hex'), c.encode('hex'), K.encode('hex'), K_compressed.encode('hex') - @classmethod - def mpk_from_seed(klass, seed): - curve = SECP256k1 - secexp = klass.stretch_key(seed) - master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) - master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') - return master_public_key - @classmethod - def stretch_key(self,seed): - oldseed = seed - for i in range(100000): - seed = hashlib.sha256(seed + oldseed).digest() - return string_to_number( seed ) - - def get_sequence(self, sequence, mpk): - for_change, n = sequence - return string_to_number( Hash( "%d:%d:"%(n,for_change) + mpk.decode('hex') ) ) - - def get_address(self, sequence): - if not self.mpk2: - pubkey = self.get_pubkey(sequence) - address = public_key_to_bc_address( pubkey.decode('hex') ) - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk = self.mpk3) - address = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)["address"] - return address - - def get_pubkey(self, sequence, mpk=None): - curve = SECP256k1 - if mpk is None: mpk = self.mpk - z = self.get_sequence(sequence, mpk) - master_public_key = ecdsa.VerifyingKey.from_string( mpk.decode('hex'), curve = SECP256k1 ) - pubkey_point = master_public_key.pubkey.point + z*curve.generator - public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 ) - return '04' + public_key2.to_string().encode('hex') - - def get_private_key_from_stretched_exponent(self, sequence, secexp): - order = generator_secp256k1.order() - secexp = ( secexp + self.get_sequence(sequence, self.mpk) ) % order - pk = number_to_string( secexp, generator_secp256k1.order() ) - compressed = False - return SecretToASecret( pk, compressed ) - - def get_private_key(self, sequence, seed): - secexp = self.stretch_key(seed) - return self.get_private_key_from_stretched_exponent(sequence, secexp) - - def get_private_keys(self, sequence_list, seed): - secexp = self.stretch_key(seed) - return [ self.get_private_key_from_stretched_exponent( sequence, secexp) for sequence in sequence_list] - - def check_seed(self, seed): - curve = SECP256k1 - secexp = self.stretch_key(seed) - master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) - master_public_key = master_private_key.get_verifying_key().to_string().encode('hex') - if master_public_key != self.mpk: - print_error('invalid password (mpk)') - raise BaseException('Invalid password') - return True - - def get_input_info(self, sequence): - if not self.mpk2: - pk_addr = self.get_address(sequence) - redeemScript = None - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence,mpk=self.mpk2) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript'] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk=self.mpk3) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)['redeemScript'] - return pk_addr, redeemScript +def bip32_public_derivation(c, K, branch, sequence): + assert sequence.startswith(branch) + sequence = sequence[len(branch):] + for n in sequence.split('/'): + n = int(n) + K, cK, c = CKD_prime(K, c, n) + return c.encode('hex'), K.encode('hex'), cK.encode('hex') -class BIP32Sequence: - def __init__(self, mpk, mpk2 = None, mpk3 = None): - self.mpk = mpk - self.mpk2 = mpk2 - self.mpk3 = mpk3 - - @classmethod - def mpk_from_seed(klass, seed): - master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) - return master_public_key.encode('hex'), master_chain.encode('hex') - - def get_pubkey(self, sequence, mpk = None): - if not mpk: mpk = self.mpk - master_public_key, master_chain = mpk - K = master_public_key.decode('hex') - chain = master_chain.decode('hex') - for i in sequence: - K, K_compressed, chain = CKD_prime(K, chain, i) - return K_compressed.encode('hex') - - def get_address(self, sequence): - if not self.mpk2: - pubkey = self.get_pubkey(sequence) - address = public_key_to_bc_address( pubkey.decode('hex') ) - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk = self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk = self.mpk3) - address = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)["address"] - return address - - def get_private_key(self, sequence, seed): - master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) - chain = master_chain - k = master_secret - for i in sequence: - k, chain = CKD(k, chain, i) - return SecretToASecret(k, True) - - def get_private_keys(self, sequence_list, seed): - return [ self.get_private_key( sequence, seed) for sequence in sequence_list] - - def check_seed(self, seed): - master_secret, master_chain, master_public_key, master_public_key_compressed = bip32_init(seed) - assert self.mpk == (master_public_key.encode('hex'), master_chain.encode('hex')) - - def get_input_info(self, sequence): - if not self.mpk2: - pk_addr = self.get_address(sequence) - redeemScript = None - elif not self.mpk3: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript'] - else: - pubkey1 = self.get_pubkey(sequence) - pubkey2 = self.get_pubkey(sequence, mpk=self.mpk2) - pubkey3 = self.get_pubkey(sequence, mpk=self.mpk3) - pk_addr = public_key_to_bc_address( pubkey1.decode('hex') ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1, pubkey2, pubkey3], 2)['redeemScript'] - return pk_addr, redeemScript ################################## transactions @@ -734,9 +594,10 @@ class Transaction: txin = self.inputs[i] tx_for_sig = self.serialize( self.inputs, self.outputs, for_sig = i ) - if txin.get('redeemScript'): + redeem_script = txin.get('redeemScript') + if redeem_script: # 1 parse the redeem script - num, redeem_pubkeys = deserialize.parse_redeemScript(txin.get('redeemScript')) + num, redeem_pubkeys = deserialize.parse_redeemScript(redeem_script) self.inputs[i]["pubkeys"] = redeem_pubkeys # build list of public/private keys @@ -747,19 +608,25 @@ class Transaction: pubkey = GetPubKey(pkey.pubkey, compressed) keypairs[ pubkey.encode('hex') ] = sec + print "keypairs", keypairs + print redeem_script, redeem_pubkeys + # list of already existing signatures signatures = txin.get("signatures",[]) print_error("signatures",signatures) for pubkey in redeem_pubkeys: - public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1) - for s in signatures: - try: - public_key.verify_digest( s.decode('hex')[:-1], Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der) - break - except ecdsa.keys.BadSignatureError: - continue - else: + + # here we have compressed key.. it won't work + #public_key = ecdsa.VerifyingKey.from_string(pubkey[2:].decode('hex'), curve = SECP256k1) + #for s in signatures: + # try: + # public_key.verify_digest( s.decode('hex')[:-1], Hash( tx_for_sig.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der) + # break + # except ecdsa.keys.BadSignatureError: + # continue + #else: + if 1: # check if we have a key corresponding to the redeem script if pubkey in keypairs.keys(): # add signature @@ -783,7 +650,6 @@ class Transaction: compressed = is_compressed(sec) pkey = regenerate_key(sec) secexp = pkey.secret - private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) public_key = private_key.get_verifying_key() pkey = EC_KEY(secexp) diff --git a/lib/simple_config.py b/lib/simple_config.py index bff785184..f8a9e00e9 100644 --- a/lib/simple_config.py +++ b/lib/simple_config.py @@ -206,7 +206,7 @@ a SimpleConfig instance then reads the wallet file. def save_wallet_config(self): # prevent the creation of incomplete wallets - if self.wallet_config.get('master_public_key') is None: + if self.wallet_config.get('master_public_keys') is None: return s = repr(self.wallet_config) diff --git a/lib/wallet.py b/lib/wallet.py index 1957d885e..0bc757ee4 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -32,7 +32,7 @@ import time from util import print_msg, print_error, user_dir, format_satoshis from bitcoin import * - +from account import * # AES encryption EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s)) @@ -85,14 +85,12 @@ class Wallet: self.imported_keys = config.get('imported_keys',{}) self.history = config.get('addr_history',{}) # address -> list(txid, height) - self.accounts = config.get('accounts', {}) # this should not include public keys - self.SequenceClass = ElectrumSequence - self.sequences = {} - self.sequences[0] = self.SequenceClass(self.config.get('master_public_key')) - if self.accounts.get(0) is None: - self.accounts[0] = { 0:[], 1:[], 'name':'Main account' } + self.master_public_keys = config.get('master_public_keys',{}) + self.master_private_keys = config.get('master_private_keys', {}) + + self.load_accounts(config) self.transactions = {} tx = config.get('transactions',{}) @@ -167,18 +165,88 @@ class Wallet: seed = random_seed(128) self.seed = seed + def save_seed(self): self.config.set_key('seed', self.seed, True) self.config.set_key('seed_version', self.seed_version, True) - mpk = self.SequenceClass.mpk_from_seed(self.seed) - self.init_sequence(mpk) + + master_k, master_c, master_K, master_cK = bip32_init(self.seed) + + k0, c0, K0, cK0 = bip32_private_derivation(master_k, master_c, "m/", "m/0'/") + k1, c1, K1, cK1 = bip32_private_derivation(master_k, master_c, "m/", "m/1'/") + k2, c2, K2, cK2 = bip32_private_derivation(master_k, master_c, "m/", "m/2'/") + + self.master_public_keys = { + "m/0'/": (c0, K0, cK0), + "m/1'/": (c1, K1, cK1), + "m/2'/": (c2, K2, cK2) + } + + self.master_private_keys = { + "m/0'/": k0, + "m/1'/": k1 + } + # send k2 to service + + self.config.set_key('master_public_keys', self.master_public_keys, True) + self.config.set_key('master_private_keys', self.master_private_keys, True) + + # create default account + self.create_new_account('Main account') + + + def create_new_account(self, name): + keys = self.accounts.keys() + i = 0 + + while True: + derivation = "m/0'/%d'"%i + if derivation not in keys: break + i += 1 + + start = "m/0'/" + master_c, master_K, master_cK = self.master_public_keys[start] + master_k = self.master_private_keys[start] # needs decryption + k, c, K, cK = bip32_private_derivation(master_k, master_c, start, derivation) # this is a type 1 derivation + + self.accounts[derivation] = BIP32_Account({ 'name':name, 'c':c, 'K':K, 'cK':cK }) + self.save_accounts() + + def create_p2sh_account(self, name): + keys = self.accounts.keys() + i = 0 + while True: + account_id = "m/1'/%d & m/2'/%d"%(i,i) + if account_id not in keys: break + i += 1 + + master_c1, master_K1, _ = self.master_public_keys["m/1'/"] + c1, K1, cK1 = bip32_public_derivation(master_c1.decode('hex'), master_K1.decode('hex'), "m/1'/", "m/1'/%d"%i) + + master_c2, master_K2, _ = self.master_public_keys["m/2'/"] + c2, K2, cK2 = bip32_public_derivation(master_c2.decode('hex'), master_K2.decode('hex'), "m/2'/", "m/2'/%d"%i) + + self.accounts[account_id] = BIP32_Account_2of2({ 'name':name, 'c':c1, 'K':K1, 'cK':cK1, 'c2':c2, 'K2':K2, 'cK2':cK2 }) + self.save_accounts() + + + def save_accounts(self): + d = {} + for k, v in self.accounts.items(): + d[k] = v.dump() + self.config.set_key('accounts', d, True) + + + def load_accounts(self, config): + d = config.get('accounts', {}) + self.accounts = {} + for k, v in d.items(): + if '&' in k: + self.accounts[k] = BIP32_Account_2of2(v) + else: + self.accounts[k] = BIP32_Account(v) - def init_sequence(self, mpk): - self.config.set_key('master_public_key', mpk, True) - self.sequences[0] = self.SequenceClass(mpk) - self.accounts[0] = { 0:[], 1:[], 'name':'Main account' } - self.config.set_key('accounts', self.accounts, True) def addresses(self, include_change = True): @@ -198,6 +266,7 @@ class Wallet: return s[0] == 1 def get_master_public_key(self): + raise return self.config.get("master_public_key") def get_address_index(self, address): @@ -205,7 +274,7 @@ class Wallet: return -1, None for account in self.accounts.keys(): for for_change in [0,1]: - addresses = self.accounts[account][for_change] + addresses = self.accounts[account].get_addresses(for_change) for addr in addresses: if address == addr: return account, (for_change, addresses.index(addr)) @@ -214,12 +283,12 @@ class Wallet: def get_public_key(self, address): account, sequence = self.get_address_index(address) - return self.sequences[account].get_pubkey( sequence ) + return self.accounts[account].get_pubkey( sequence ) def decode_seed(self, password): seed = pw_decode(self.seed, password) - self.sequences[0].check_seed(seed) + #todo: #self.sequences[0].check_seed(seed) return seed def get_private_key(self, address, password): @@ -230,19 +299,27 @@ class Wallet: # decode seed in any case, in order to test the password seed = self.decode_seed(password) out = {} - l_sequences = [] - l_addresses = [] for address in addresses: if address in self.imported_keys.keys(): out[address] = pw_decode( self.imported_keys[address], password ) else: account, sequence = self.get_address_index(address) - if account == 0: - l_sequences.append(sequence) - l_addresses.append(address) + print "found index", address, account, sequence + if account == "m/0'/0'": + # FIXME: this is ugly + master_k = self.master_private_keys["m/0'/"] + master_c, _, _ = self.master_public_keys["m/0'/"] + master_k, master_c = CKD(master_k, master_c, 0 + BIP32_PRIME) + pk = self.accounts["m/0'/0'"].get_private_key(sequence, master_k) + out[address] = pk + + elif account == "m/1'/1 & m/2'/1": + master_k = self.master_private_keys["m/1'/"] + master_c, master_K, _ = self.master_public_keys["m/1'/"] + master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), 1) + pk = self.accounts[account].get_private_key(sequence, master_k) + out[address] = pk - pk = self.sequences[0].get_private_keys(l_sequences, seed) - for i, address in enumerate(l_addresses): out[address] = pk[i] return out @@ -281,8 +358,8 @@ class Wallet: if txin.get('KeyID'): account, name, sequence = txin.get('KeyID') if name != 'Electrum': continue - sec = self.sequences[account].get_private_key(sequence, seed) - addr = self.sequences[account].get_address(sequence) + sec = self.accounts[account].get_private_key(sequence, seed) + addr = self.accounts[account].get_address(sequence) txin['address'] = addr private_keys[addr] = sec @@ -313,20 +390,6 @@ class Wallet: print_error("Verification error: {0}".format(e)) return False - def create_new_address(self, account, for_change): - addresses = self.accounts[account][for_change] - n = len(addresses) - address = self.get_new_address( account, for_change, n) - self.accounts[account][for_change].append(address) - self.history[address] = [] - print_msg(address) - return address - - - def get_new_address(self, account, for_change, n): - return self.sequences[account].get_address((for_change, n)) - print address - return address def change_gap_limit(self, value): if value >= self.gap_limit: @@ -345,7 +408,7 @@ class Wallet: self.gap_limit = value self.config.set_key('gap_limit', self.gap_limit, True) - self.config.set_key('accounts', self.accounts, True) + self.save_accounts() return True else: return False @@ -363,7 +426,7 @@ class Wallet: nmax = 0 for account in self.accounts.values(): - addresses = account[0] + addresses = account.get_addresses(0) k = self.num_unused_trailing_addresses(addresses) for a in addresses[0:-k]: if self.history.get(a): @@ -391,16 +454,22 @@ class Wallet: def synchronize_sequence(self, account, for_change): limit = self.gap_limit_for_change if for_change else self.gap_limit - addresses = self.accounts[account][for_change] new_addresses = [] while True: + addresses = account.get_addresses(for_change) if len(addresses) < limit: - new_addresses.append( self.create_new_address(account, for_change) ) + address = account.create_new_address(for_change) + self.history[address] = [] + new_addresses.append( address ) continue + if map( lambda a: self.address_is_old(a), addresses[-limit:] ) == limit*[False]: break else: - new_addresses.append( self.create_new_address(account, for_change) ) + address = account.create_new_address(for_change) + self.history[address] = [] + new_addresses.append( address ) + return new_addresses @@ -412,10 +481,10 @@ class Wallet: def synchronize(self): new = [] - for account in self.accounts.keys(): + for account in self.accounts.values(): new += self.synchronize_account(account) if new: - self.config.set_key('accounts', self.accounts, True) + self.save_accounts() self.config.set_key('addr_history', self.history, True) return new @@ -522,7 +591,7 @@ class Wallet: def get_accounts(self): accounts = {} for k, account in self.accounts.items(): - accounts[k] = account.get('name') + accounts[k] = account.name if self.imported_keys: accounts[-1] = 'Imported keys' return accounts @@ -534,8 +603,8 @@ class Wallet: o = self.imported_keys.keys() else: ac = self.accounts[a] - o = ac[0][:] - if include_change: o += ac[1] + o = ac.get_addresses(0) + if include_change: o += ac.get_addresses(1) return o def get_imported_balance(self): @@ -818,14 +887,20 @@ class Wallet: pk_addresses.append(address) continue account, sequence = self.get_address_index(address) - txin['KeyID'] = (account, 'Electrum', sequence) # used by the server to find the key - pk_addr, redeemScript = self.sequences[account].get_input_info(sequence) + + txin['KeyID'] = (account, 'BIP32', sequence) # used by the server to find the key + + _, redeemScript = self.accounts[account].get_input_info(sequence) + if redeemScript: txin['redeemScript'] = redeemScript - pk_addresses.append(pk_addr) + pk_addresses.append(address) + + print "pk_addresses", pk_addresses # get all private keys at once. if self.seed: private_keys = self.get_private_keys(pk_addresses, password) + print "private keys", private_keys tx.sign(private_keys) for address, x in outputs: @@ -920,7 +995,6 @@ class Wallet: s = { 'use_change': self.use_change, 'fee_per_kb': self.fee, - 'accounts': self.accounts, 'addr_history': self.history, 'labels': self.labels, 'contacts': self.addressbook, From de03fbbb12dcfd6ce44faeb701f6c773198046d7 Mon Sep 17 00:00:00 2001 From: thomasv Date: Sat, 3 Aug 2013 17:30:59 +0200 Subject: [PATCH 05/11] add account module --- lib/__init__.py | 1 + setup.py | 1 + 2 files changed, 2 insertions(+) diff --git a/lib/__init__.py b/lib/__init__.py index c3100ecf5..f162a9441 100644 --- a/lib/__init__.py +++ b/lib/__init__.py @@ -6,6 +6,7 @@ from verifier import WalletVerifier from interface import Interface, pick_random_server, DEFAULT_SERVERS from simple_config import SimpleConfig import bitcoin +import account from bitcoin import Transaction, EC_KEY, is_valid from mnemonic import mn_encode as mnemonic_encode from mnemonic import mn_decode as mnemonic_decode diff --git a/setup.py b/setup.py index aed56987c..d79dc10da 100644 --- a/setup.py +++ b/setup.py @@ -64,6 +64,7 @@ setup(name = "Electrum", 'electrum.socks', 'electrum.msqr', 'electrum.util', + 'electrum.account', 'electrum.bitcoin', 'electrum.deserialize', 'electrum.verifier', From 553493364e5241463b1582a716c772456a307a39 Mon Sep 17 00:00:00 2001 From: thomasv Date: Sun, 4 Aug 2013 16:46:47 +0200 Subject: [PATCH 06/11] get_new_address -> get_address --- lib/account.py | 17 ++++++----------- lib/wallet.py | 4 ++-- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/lib/account.py b/lib/account.py index b734d1447..85a3471f3 100644 --- a/lib/account.py +++ b/lib/account.py @@ -35,12 +35,12 @@ class Account(object): def create_new_address(self, for_change): addresses = self.change if for_change else self.addresses n = len(addresses) - address = self.get_new_address( for_change, n) + address = self.get_address( for_change, n) addresses.append(address) print address return address - def get_new_address(self, for_change, n): + def get_address(self, for_change, n): pass @@ -156,7 +156,7 @@ class BIP32_Account(Account): d['cK'] = self.cK.encode('hex') return d - def get_new_address(self, for_change, n): + def get_address(self, for_change, n): pubkey = self.get_pubkey(for_change, n) address = public_key_to_bc_address( pubkey ) return address @@ -168,12 +168,6 @@ class BIP32_Account(Account): K, K_compressed, chain = CKD_prime(K, chain, i) return K_compressed - def get_address(self, sequence): - for_change, n = sequence - pubkey = self.get_pubkey(for_change, n) - address = public_key_to_bc_address( pubkey ) - return address - def get_private_key(self, sequence, master_k): chain = self.c k = master_k @@ -189,7 +183,8 @@ class BIP32_Account(Account): assert self.mpk == (master_public_key.encode('hex'), master_chain.encode('hex')) def get_input_info(self, sequence): - pk_addr = self.get_address(sequence) + chain, i = sequence + pk_addr = self.get_address(chain, i) redeemScript = None return pk_addr, redeemScript @@ -217,7 +212,7 @@ class BIP32_Account_2of2(BIP32_Account): K, K_compressed, chain = CKD_prime(K, chain, i) return K_compressed - def get_new_address(self, for_change, n): + def get_address(self, for_change, n): pubkey1 = self.get_pubkey(for_change, n) pubkey2 = self.get_pubkey2(for_change, n) address = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)["address"] diff --git a/lib/wallet.py b/lib/wallet.py index 0bc757ee4..d5da6b31a 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -313,10 +313,10 @@ class Wallet: pk = self.accounts["m/0'/0'"].get_private_key(sequence, master_k) out[address] = pk - elif account == "m/1'/1 & m/2'/1": + elif account == "m/1'/0 & m/2'/0": master_k = self.master_private_keys["m/1'/"] master_c, master_K, _ = self.master_public_keys["m/1'/"] - master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), 1) + master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), 0) pk = self.accounts[account].get_private_key(sequence, master_k) out[address] = pk From 77df84e509ccf8e2ef244972d70f165138b1e59d Mon Sep 17 00:00:00 2001 From: ThomasV Date: Mon, 5 Aug 2013 12:08:54 +0200 Subject: [PATCH 07/11] make wallet.get_private_keys more general --- lib/wallet.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/wallet.py b/lib/wallet.py index d5da6b31a..45c8d9d8d 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -304,19 +304,23 @@ class Wallet: out[address] = pw_decode( self.imported_keys[address], password ) else: account, sequence = self.get_address_index(address) - print "found index", address, account, sequence - if account == "m/0'/0'": - # FIXME: this is ugly + print_error( "found index", address, account, sequence) + + m = re.match("m/0'/(\d+)'", account) + if m: + num = int(m.group(1)) master_k = self.master_private_keys["m/0'/"] master_c, _, _ = self.master_public_keys["m/0'/"] - master_k, master_c = CKD(master_k, master_c, 0 + BIP32_PRIME) - pk = self.accounts["m/0'/0'"].get_private_key(sequence, master_k) + master_k, master_c = CKD(master_k, master_c, num + BIP32_PRIME) + pk = self.accounts[account].get_private_key(sequence, master_k) out[address] = pk - elif account == "m/1'/0 & m/2'/0": + m2 = re.match("m/1'/(\d+) & m/2'/(\d+)", account) + if m2: + num = int(m2.group(1)) master_k = self.master_private_keys["m/1'/"] master_c, master_K, _ = self.master_public_keys["m/1'/"] - master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), 0) + master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), num) pk = self.accounts[account].get_private_key(sequence, master_k) out[address] = pk From d9a926b0ff52c5d25a99f5c4875b6116b14d53f0 Mon Sep 17 00:00:00 2001 From: ThomasV Date: Mon, 5 Aug 2013 13:53:50 +0200 Subject: [PATCH 08/11] encryption of bip32 master private keys --- lib/account.py | 33 ++++++++++++----------- lib/wallet.py | 73 +++++++++++++++++++++++++++++++------------------- 2 files changed, 63 insertions(+), 43 deletions(-) diff --git a/lib/account.py b/lib/account.py index 85a3471f3..63c5a2981 100644 --- a/lib/account.py +++ b/lib/account.py @@ -1,18 +1,21 @@ -""" -todolist: - * passwords, private keys storage - * multisig service - * compatibility with old addresses for restore - * gui - - an account may use one or several MPKs. - due to the type 1 derivations, we need to pass the mpk to this function - None : all accounts - -1 : imported - 0,1... : seeded sequences - - each account has a public and private master key -""" +#!/usr/bin/env python +# +# Electrum - lightweight Bitcoin client +# Copyright (C) 2013 thomasv@gitorious +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + from bitcoin import * diff --git a/lib/wallet.py b/lib/wallet.py index 45c8d9d8d..4189c0b20 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -195,7 +195,7 @@ class Wallet: self.create_new_account('Main account') - def create_new_account(self, name): + def create_new_account(self, name, password): keys = self.accounts.keys() i = 0 @@ -205,9 +205,9 @@ class Wallet: i += 1 start = "m/0'/" + master_k = self.get_master_private_key(start, password ) master_c, master_K, master_cK = self.master_public_keys[start] - master_k = self.master_private_keys[start] # needs decryption - k, c, K, cK = bip32_private_derivation(master_k, master_c, start, derivation) # this is a type 1 derivation + k, c, K, cK = bip32_private_derivation(master_k, master_c, start, derivation) self.accounts[derivation] = BIP32_Account({ 'name':name, 'c':c, 'K':K, 'cK':cK }) self.save_accounts() @@ -269,6 +269,17 @@ class Wallet: raise return self.config.get("master_public_key") + def get_master_private_key(self, account, password): + master_k = pw_decode( self.master_private_keys[account], password) + master_c, master_K, master_Kc = self.master_public_keys[account] + try: + K, Kc = get_pubkeys_from_secret(master_k.decode('hex')) + assert K.encode('hex') == master_K + except: + raise BaseException("Invalid password") + return master_k + + def get_address_index(self, address): if address in self.imported_keys.keys(): return -1, None @@ -291,8 +302,29 @@ class Wallet: #todo: #self.sequences[0].check_seed(seed) return seed + def get_private_key(self, address, password): - return self.get_private_keys([address], password).get(address) + if address in self.imported_keys.keys(): + return pw_decode( self.imported_keys[address], password ) + else: + account, sequence = self.get_address_index(address) + m = re.match("m/0'/(\d+)'", account) + if m: + num = int(m.group(1)) + master_k = self.get_master_private_key("m/0'/", password) + master_c, _, _ = self.master_public_keys["m/0'/"] + master_k, master_c = CKD(master_k, master_c, num + BIP32_PRIME) + return self.accounts[account].get_private_key(sequence, master_k) + + m2 = re.match("m/1'/(\d+) & m/2'/(\d+)", account) + if m2: + num = int(m2.group(1)) + master_k = self.get_master_private_key("m/1'/", password) + master_c, master_K, _ = self.master_public_keys["m/1'/"] + master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), num) + return self.accounts[account].get_private_key(sequence, master_k) + return + def get_private_keys(self, addresses, password): if not self.seed: return {} @@ -300,29 +332,8 @@ class Wallet: seed = self.decode_seed(password) out = {} for address in addresses: - if address in self.imported_keys.keys(): - out[address] = pw_decode( self.imported_keys[address], password ) - else: - account, sequence = self.get_address_index(address) - print_error( "found index", address, account, sequence) - - m = re.match("m/0'/(\d+)'", account) - if m: - num = int(m.group(1)) - master_k = self.master_private_keys["m/0'/"] - master_c, _, _ = self.master_public_keys["m/0'/"] - master_k, master_c = CKD(master_k, master_c, num + BIP32_PRIME) - pk = self.accounts[account].get_private_key(sequence, master_k) - out[address] = pk - - m2 = re.match("m/1'/(\d+) & m/2'/(\d+)", account) - if m2: - num = int(m2.group(1)) - master_k = self.master_private_keys["m/1'/"] - master_c, master_K, _ = self.master_public_keys["m/1'/"] - master_k, master_c = CKD(master_k.decode('hex'), master_c.decode('hex'), num) - pk = self.accounts[account].get_private_key(sequence, master_k) - out[address] = pk + pk = self.get_private_key(address, password) + if pk: out[address] = pk return out @@ -724,7 +735,7 @@ class Wallet: if not self.use_change or account == -1: change_addr = inputs[-1]['address'] else: - change_addr = self.accounts[account][1][-self.gap_limit_for_change] + change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change] # Insert the change output at a random position in the outputs posn = random.randint(0, len(outputs)) @@ -949,6 +960,12 @@ class Wallet: self.imported_keys[k] = c self.config.set_key('imported_keys', self.imported_keys, True) + for k, v in self.master_private_keys.items(): + b = pw_decode(v, old_password) + c = pw_encode(b, new_password) + self.master_private_keys[k] = c + self.config.set_key('master_private_keys', self.master_private_keys, True) + def freeze(self,addr): if self.is_mine(addr) and addr not in self.frozen_addresses: From 111611a08b5fd13f2e858495632cf0eff65f634b Mon Sep 17 00:00:00 2001 From: ThomasV Date: Mon, 5 Aug 2013 17:15:01 +0200 Subject: [PATCH 09/11] plugins: do not overload __init__, use init() instead --- gui/gui_classic.py | 12 +++++----- gui/plugins.py | 41 ++++++++++++++++++++++----------- lib/version.py | 2 +- plugins/aliases.py | 8 +++++-- plugins/labels.py | 47 +++++++++++++++++++------------------- plugins/pointofsale.py | 25 ++++++++++---------- plugins/qrscanner.py | 10 +++++--- plugins/virtualkeyboard.py | 9 ++++++-- 8 files changed, 92 insertions(+), 62 deletions(-) diff --git a/gui/gui_classic.py b/gui/gui_classic.py index b02f26bd8..e427f0dd9 100644 --- a/gui/gui_classic.py +++ b/gui/gui_classic.py @@ -345,7 +345,8 @@ class ElectrumWindow(QMainWindow): self.notify_transactions() # plugins that need to change the GUI do it here - self.run_hook('init_gui') + self.run_hook('init') + def select_wallet_file(self): wallet_folder = self.wallet.config.path @@ -494,9 +495,9 @@ class ElectrumWindow(QMainWindow): plugins = [ __import__('electrum_plugins.'+name, fromlist=['electrum_plugins']) for name in plugin_names] self.plugins = [] - for p in plugins: + for name, p in zip(plugin_names, plugins): try: - self.plugins.append( p.Plugin(self) ) + self.plugins.append( p.Plugin(self, name) ) except: print_msg("Error:cannot initialize plugin",p) traceback.print_exc(file=sys.stdout) @@ -2161,15 +2162,14 @@ class ElectrumWindow(QMainWindow): return lambda: cb.setChecked(p.toggle()) for i, p in enumerate(self.plugins): try: - name, description = p.get_info() - cb = QCheckBox(name) + cb = QCheckBox(p.fullname()) cb.setDisabled(not p.is_available()) cb.setChecked(p.is_enabled()) cb.clicked.connect(mk_toggle(cb,p)) grid_plugins.addWidget(cb, i, 0) if p.requires_settings(): grid_plugins.addWidget(EnterButton(_('Settings'), p.settings_dialog), i, 1) - grid_plugins.addWidget(HelpButton(description), i, 2) + grid_plugins.addWidget(HelpButton(p.description()), i, 2) except: print_msg("Error: cannot display plugin", p) traceback.print_exc(file=sys.stdout) diff --git a/gui/plugins.py b/gui/plugins.py index e7ec00489..e9e99160f 100644 --- a/gui/plugins.py +++ b/gui/plugins.py @@ -2,27 +2,42 @@ class BasePlugin: - def get_info(self): - return self.fullname, self.description - - def __init__(self, gui, name, fullname, description): - self.name = name - self.fullname = fullname - self.description = description + def __init__(self, gui, name): self.gui = gui + self.name = name self.config = gui.config + def fullname(self): + return self.name + + def description(self): + return 'undefined' + def requires_settings(self): return False def toggle(self): - enabled = not self.is_enabled() - self.set_enabled(enabled) - self.init_gui() - return enabled + if self.is_enabled(): + if self.disable(): + self.close() + else: + if self.enable(): + self.init() + + return self.is_enabled() + - def init_gui(self): - pass + def enable(self): + self.set_enabled(True) + return True + + def disable(self): + self.set_enabled(False) + return True + + def init(self): pass + + def close(self): pass def is_enabled(self): return self.is_available() and self.config.get('use_'+self.name) is True diff --git a/lib/version.py b/lib/version.py index 172b9b25e..3d72061cf 100644 --- a/lib/version.py +++ b/lib/version.py @@ -1,4 +1,4 @@ -ELECTRUM_VERSION = "1.8.1" # version of the client package +ELECTRUM_VERSION = "1.9" # version of the client package PROTOCOL_VERSION = '0.6' # protocol version requested SEED_VERSION = 4 # bump this every time the seed generation is modified TRANSLATION_ID = 4101 # version of the wiki page diff --git a/plugins/aliases.py b/plugins/aliases.py index e67f1d6d6..2cfac48d0 100644 --- a/plugins/aliases.py +++ b/plugins/aliases.py @@ -20,13 +20,17 @@ ALIAS_REGEXP = '^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$' from electrum_gui import BasePlugin class Plugin(BasePlugin): - def __init__(self, gui): - BasePlugin.__init__(self, gui, 'aliases', 'Aliases', _('Retrieve aliases using http.')) + def fullname(self): return 'Aliases' + + def description(self): return _('Retrieve aliases using http.') + + def init(self): self.aliases = self.config.get('aliases', {}) # aliases for addresses self.authorities = self.config.get('authorities', {}) # trusted addresses self.receipts = self.config.get('receipts',{}) # signed URIs + def timer_actions(self): if self.gui.payto_e.hasFocus(): return diff --git a/plugins/labels.py b/plugins/labels.py index 20e4fa93c..fb51b1662 100644 --- a/plugins/labels.py +++ b/plugins/labels.py @@ -21,6 +21,13 @@ from electrum_gui.i18n import _ from electrum_gui.gui_classic import HelpButton class Plugin(BasePlugin): + + def fullname(self): + return _('Label Sync') + + def description(self): + return '%s\n\n%s%s%s' % (_("This plugin can sync your labels across multiple Electrum installs by using a remote database to save your data. Labels, transactions and addresses are all sent and stored encrypted on the remote server. This code might increase the load of your wallet with a few microseconds as it will sync labels on each startup."), _("To get started visit"), " http://labelectrum.herokuapp.com/", _(" to sign up for an account.")) + def version(self): return "0.2.1" @@ -35,34 +42,32 @@ class Plugin(BasePlugin): return decoded_message - def __init__(self, gui): - self.target_host = 'labelectrum.herokuapp.com' - BasePlugin.__init__(self, gui, 'labels', _('Label Sync'), '%s\n\n%s%s%s' % (_("This plugin can sync your labels across multiple Electrum installs by using a remote database to save your data. Labels, transactions and addresses are all sent and stored encrypted on the remote server. This code might increase the load of your wallet with a few microseconds as it will sync labels on each startup."), _("To get started visit"), " http://labelectrum.herokuapp.com/", _(" to sign up for an account."))) + def init(self): + self.target_host = 'labelectrum.herokuapp.com' self.wallet = gui.wallet self.gui = gui self.config = gui.config self.labels = self.wallet.labels self.transactions = self.wallet.transactions - self.encode_password = hashlib.sha1(self.config.get("master_public_key")).digest().encode('hex')[:32] - - self.wallet_id = hashlib.sha256(str(self.config.get("master_public_key"))).digest().encode('hex') + mpk = self.wallet.master_public_keys["m/0'/"][1] + self.encode_password = hashlib.sha1(mpk).digest().encode('hex')[:32] + self.wallet_id = hashlib.sha256(mpk).digest().encode('hex') addresses = [] - for k, account in self.wallet.accounts.items(): - for address in account[0]: + for account in self.wallet.accounts.values(): + for address in account.get_addresses(0): addresses.append(address) self.addresses = addresses - def auth_token(self): - return self.config.get("plugin_label_api_key") - - def init_gui(self): - if self.is_enabled() and self.auth_token(): + if self.auth_token(): # If there is an auth token we can try to actually start syncing self.full_pull() + def auth_token(self): + return self.config.get("plugin_label_api_key") + def is_available(self): return True @@ -138,18 +143,14 @@ class Plugin(BasePlugin): else: return False - def toggle(self): - enabled = not self.is_enabled() - self.set_enabled(enabled) - self.init_gui() - - if not self.auth_token() and enabled: # First run, throw plugin settings in your face + def enable(self): + if not self.auth_token(): # First run, throw plugin settings in your face if self.settings_dialog(): - self.set_enabled(True) - return True + self.set_enabled(True) + return True else: - self.set_enabled(False) - return False + self.set_enabled(False) + return False return enabled def full_push(self): diff --git a/plugins/pointofsale.py b/plugins/pointofsale.py index c408e4ab0..40262154c 100644 --- a/plugins/pointofsale.py +++ b/plugins/pointofsale.py @@ -93,23 +93,24 @@ class QR_Window(QWidget): class Plugin(BasePlugin): - def __init__(self, gui): - BasePlugin.__init__(self, gui, 'pointofsale', 'Point of Sale', - _('Show QR code window and amounts requested for each address. Add menu item to request amount.') ) + def fullname(self): + return 'Point of Sale' + + def description(self): + return _('Show QR code window and amounts requested for each address. Add menu item to request amount.') + + def init(self): self.qr_window = None self.requested_amounts = self.config.get('requested_amounts',{}) self.merchant_name = self.config.get('merchant_name', 'Invoice') + self.gui.expert_mode = True + self.gui.receive_list.setHeaderLabels([ _('Address'), _('Label'), _('Balance'), _('Request')]) + self.toggle_QR_window(True) - def init_gui(self): - enabled = self.is_enabled() - if enabled: - self.gui.expert_mode = True - self.gui.receive_list.setHeaderLabels([ _('Address'), _('Label'), _('Balance'), _('Request')]) - else: - self.gui.receive_list.setHeaderLabels([ _('Address'), _('Label'), _('Balance'), _('Tx')]) - - self.toggle_QR_window(enabled) + def close(self): + self.gui.receive_list.setHeaderLabels([ _('Address'), _('Label'), _('Balance'), _('Tx')]) + self.toggle_QR_window(False) def close_main_window(self): diff --git a/plugins/qrscanner.py b/plugins/qrscanner.py index fb2917d78..c3044642d 100644 --- a/plugins/qrscanner.py +++ b/plugins/qrscanner.py @@ -18,10 +18,14 @@ except ImportError: from electrum_gui import BasePlugin class Plugin(BasePlugin): - def __init__(self, gui): - BasePlugin.__init__(self, gui, 'qrscans', 'QR scans', "QR Scans.\nInstall the zbar package (http://zbar.sourceforge.net/download.html) to enable this plugin") + def fullname(self): return 'QR scans' + + def description(self): return "QR Scans.\nInstall the zbar package (http://zbar.sourceforge.net/download.html) to enable this plugin" + + def __init__(self, gui, name): + BasePlugin.__init__(self, gui, name) self._is_available = self._init() - + def _init(self): if not zbar: return False diff --git a/plugins/virtualkeyboard.py b/plugins/virtualkeyboard.py index ed7e16ad5..6d081a086 100644 --- a/plugins/virtualkeyboard.py +++ b/plugins/virtualkeyboard.py @@ -5,8 +5,13 @@ from electrum_gui.i18n import _ class Plugin(BasePlugin): - def __init__(self, gui): - BasePlugin.__init__(self, gui, 'virtualkeyboard', 'Virtual Keyboard', '%s\n%s' % (_("Add an optional, mouse keyboard to the password dialog."), _("Warning: do not use this if it makes you pick a weaker password."))) + def fullname(self): + return 'Virtual Keyboard' + + def description(self): + return '%s\n%s' % (_("Add an optional, mouse keyboard to the password dialog."), _("Warning: do not use this if it makes you pick a weaker password.")) + + def init(self): self.vkb = None self.vkb_index = 0 From bc6e2e18f110ad2b99b2f5f0b611088f26aea2fb Mon Sep 17 00:00:00 2001 From: ThomasV Date: Wed, 7 Aug 2013 20:04:43 +0200 Subject: [PATCH 10/11] hex encode the output of account.get_pubkey() --- lib/account.py | 10 +++++----- lib/wallet.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/account.py b/lib/account.py index 63c5a2981..1b59ef0dc 100644 --- a/lib/account.py +++ b/lib/account.py @@ -161,7 +161,7 @@ class BIP32_Account(Account): def get_address(self, for_change, n): pubkey = self.get_pubkey(for_change, n) - address = public_key_to_bc_address( pubkey ) + address = public_key_to_bc_address( pubkey.decode('hex') ) return address def get_pubkey(self, for_change, n): @@ -169,7 +169,7 @@ class BIP32_Account(Account): chain = self.c for i in [for_change, n]: K, K_compressed, chain = CKD_prime(K, chain, i) - return K_compressed + return K_compressed.encode('hex') def get_private_key(self, sequence, master_k): chain = self.c @@ -213,12 +213,12 @@ class BIP32_Account_2of2(BIP32_Account): chain = self.c2 for i in [for_change, n]: K, K_compressed, chain = CKD_prime(K, chain, i) - return K_compressed + return K_compressed.encode('hex') def get_address(self, for_change, n): pubkey1 = self.get_pubkey(for_change, n) pubkey2 = self.get_pubkey2(for_change, n) - address = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)["address"] + address = Transaction.multisig_script([pubkey1, pubkey2], 2)["address"] return address def get_input_info(self, sequence): @@ -227,6 +227,6 @@ class BIP32_Account_2of2(BIP32_Account): pubkey2 = self.get_pubkey2(chain, i) # fixme pk_addr = None # public_key_to_bc_address( pubkey1 ) # we need to return that address to get the right private key - redeemScript = Transaction.multisig_script([pubkey1.encode('hex'), pubkey2.encode('hex')], 2)['redeemScript'] + redeemScript = Transaction.multisig_script([pubkey1, pubkey2], 2)['redeemScript'] return pk_addr, redeemScript diff --git a/lib/wallet.py b/lib/wallet.py index 4189c0b20..bd51b1265 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -294,7 +294,7 @@ class Wallet: def get_public_key(self, address): account, sequence = self.get_address_index(address) - return self.accounts[account].get_pubkey( sequence ) + return self.accounts[account].get_pubkey( *sequence ) def decode_seed(self, password): From 4d02b9b7b43555aa3a657a60c68171edfd03ce4f Mon Sep 17 00:00:00 2001 From: ThomasV Date: Wed, 7 Aug 2013 21:53:05 +0200 Subject: [PATCH 11/11] fix create_new_account --- gui/gui_classic.py | 21 +++++++++++++++------ lib/wallet.py | 2 +- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/gui/gui_classic.py b/gui/gui_classic.py index e427f0dd9..5d77bc651 100644 --- a/gui/gui_classic.py +++ b/gui/gui_classic.py @@ -1429,15 +1429,24 @@ class ElectrumWindow(QMainWindow): else: QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK')) + def new_account_dialog(self): text, ok = QInputDialog.getText(self, _('New Account'), _('Name') + ':') + if not ok or not text: + return name = unicode(text) - if ok: - self.wallet.create_new_account(name) - self.wallet.synchronize() - self.update_contacts_tab() - self.update_history_tab() - self.update_completions() + try: + self.create_new_account(name) + except: + QMessageBox.warning(self, _('Error'), _('Incorrect Password'), _('OK')) + + @protected + def create_new_account(self, name, password): + self.wallet.create_new_account(name, password) + self.wallet.synchronize() + self.update_receive_tab() + self.update_history_tab() + self.update_completions() def show_master_public_key(self): dialog = QDialog(self) diff --git a/lib/wallet.py b/lib/wallet.py index bd51b1265..8303e1470 100644 --- a/lib/wallet.py +++ b/lib/wallet.py @@ -192,7 +192,7 @@ class Wallet: self.config.set_key('master_private_keys', self.master_private_keys, True) # create default account - self.create_new_account('Main account') + self.create_new_account('Main account', None) def create_new_account(self, name, password):