fix bug with the order of signatures in tx input
[electrum-nvc.git] / lib / wallet.py
index caea958..6b241c6 100644 (file)
@@ -34,7 +34,7 @@ import math
 from util import print_msg, print_error, format_satoshis
 from bitcoin import *
 from account import *
-from transaction import Transaction
+from transaction import Transaction, is_extended_pubkey
 from plugins import run_hook
 import bitcoin
 from synchronizer import WalletSynchronizer
@@ -42,29 +42,8 @@ from synchronizer import WalletSynchronizer
 COINBASE_MATURITY = 100
 DUST_THRESHOLD = 5430
 
-# AES encryption
-EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
-DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
-
-def pw_encode(s, password):
-    if password:
-        secret = Hash(password)
-        return EncodeAES(secret, s)
-    else:
-        return s
-
-def pw_decode(s, password):
-    if password is not None:
-        secret = Hash(password)
-        try:
-            d = DecodeAES(secret, s)
-        except Exception:
-            raise Exception('Invalid password')
-        return d
-    else:
-        return s
-
-
+# internal ID for imported account
+IMPORTED_ACCOUNT = '/x'
 
 
 
@@ -139,7 +118,7 @@ class WalletStorage:
         with self.lock:
             if value is not None:
                 self.data[key] = value
-            else:
+            elif key in self.data:
                 self.data.pop(key)
             if save: 
                 self.write()
@@ -242,11 +221,40 @@ class Abstract_Wallet:
     def get_action(self):
         pass
 
+
+    def convert_imported_keys(self, password):
+        for k, v in self.imported_keys.items():
+            sec = pw_decode(v, password)
+            pubkey = public_key_from_private_key(sec)
+            address = public_key_to_bc_address(pubkey.decode('hex'))
+            assert address == k
+            self.import_key(sec, password)
+            self.imported_keys.pop(k)
+        self.storage.put('imported_keys', self.imported_keys)
+
+
     def load_accounts(self):
         self.accounts = {}
         self.imported_keys = self.storage.get('imported_keys',{})
-        if self.imported_keys:
-            self.accounts[-1] = ImportedAccount(self.imported_keys)
+
+        d = self.storage.get('accounts', {})
+        for k, v in d.items():
+            if k == 0:
+                v['mpk'] = self.storage.get('master_public_key')
+                self.accounts[k] = OldAccount(v)
+            elif v.get('imported'):
+                self.accounts[k] = ImportedAccount(v)
+            elif v.get('xpub3'):
+                self.accounts[k] = BIP32_Account_2of3(v)
+            elif v.get('xpub2'):
+                self.accounts[k] = BIP32_Account_2of2(v)
+            elif v.get('xpub'):
+                self.accounts[k] = BIP32_Account(v)
+            elif v.get('pending'):
+                self.accounts[k] = PendingAccount(v)
+            else:
+                print_error("cannot load account", v)
+
 
     def synchronize(self):
         pass
@@ -254,14 +262,9 @@ class Abstract_Wallet:
     def can_create_accounts(self):
         return False
 
-    def check_password(self, password):
-        raise
-
-
     def set_up_to_date(self,b):
         with self.lock: self.up_to_date = b
 
-
     def is_up_to_date(self):
         with self.lock: return self.up_to_date
 
@@ -271,21 +274,31 @@ class Abstract_Wallet:
         while not self.is_up_to_date(): 
             time.sleep(0.1)
 
+    def is_imported(self, addr):
+        account = self.accounts.get(IMPORTED_ACCOUNT)
+        if account: 
+            return addr in account.get_addresses(0)
+        else:
+            return False
+
+    def has_imported_keys(self):
+        account = self.accounts.get(IMPORTED_ACCOUNT)
+        return account is not None
 
     def import_key(self, sec, password):
-        self.check_password(password)
         try:
-            address = address_from_private_key(sec)
+            pubkey = public_key_from_private_key(sec)
+            address = public_key_to_bc_address(pubkey.decode('hex'))
         except Exception:
             raise Exception('Invalid private key')
 
         if self.is_mine(address):
             raise Exception('Address already in wallet')
         
-        # store the originally requested keypair into the imported keys table
-        self.imported_keys[address] = pw_encode(sec, password )
-        self.storage.put('imported_keys', self.imported_keys, True)
-        self.accounts[-1] = ImportedAccount(self.imported_keys)
+        if self.accounts.get(IMPORTED_ACCOUNT) is None:
+            self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
+        self.accounts[IMPORTED_ACCOUNT].add(address, pubkey, sec, password)
+        self.save_accounts()
         
         if self.synchronizer:
             self.synchronizer.subscribe_to_addresses([address])
@@ -293,13 +306,11 @@ class Abstract_Wallet:
         
 
     def delete_imported_key(self, addr):
-        if addr in self.imported_keys:
-            self.imported_keys.pop(addr)
-            self.storage.put('imported_keys', self.imported_keys, True)
-            if self.imported_keys:
-                self.accounts[-1] = ImportedAccount(self.imported_keys)
-            else:
-                self.accounts.pop(-1)
+        account = self.accounts[IMPORTED_ACCOUNT]
+        account.remove(addr)
+        if not account.get_addresses(0):
+            self.accounts.pop(IMPORTED_ACCOUNT)
+        self.save_accounts()
 
 
     def set_label(self, name, text = None):
@@ -365,35 +376,15 @@ class Abstract_Wallet:
     def getpubkeys(self, addr):
         assert is_valid(addr) and self.is_mine(addr)
         account, sequence = self.get_address_index(addr)
-        if account != -1:
-            a = self.accounts[account]
-            return a.get_pubkeys( sequence )
-
+        a = self.accounts[account]
+        return a.get_pubkeys( sequence )
 
 
     def get_private_key(self, address, password):
         if self.is_watching_only():
             return []
-
-        out = []
-        if address in self.imported_keys.keys():
-            self.check_password(password)
-            out.append( pw_decode( self.imported_keys[address], password ) )
-        else:
-            seed = self.get_seed(password)
-            account_id, sequence = self.get_address_index(address)
-            account = self.accounts[account_id]
-            xpubs = account.get_master_pubkeys()
-            roots = [k for k, v in self.master_public_keys.iteritems() if v in xpubs]
-            for root in roots:
-                xpriv = self.get_master_private_key(root, password)
-                if not xpriv:
-                    continue
-                _, _, _, c, k = deserialize_xkey(xpriv)
-                pk = bip32_private_key( sequence, k, c )
-                out.append(pk)
-                    
-        return out
+        account_id, sequence = self.get_address_index(address)
+        return self.accounts[account_id].get_private_key(sequence, self, password)
 
 
     def get_public_keys(self, address):
@@ -401,76 +392,54 @@ class Abstract_Wallet:
         return self.accounts[account_id].get_pubkeys(sequence)
 
 
-    def add_keypairs_from_wallet(self, tx, keypairs, password):
+    def add_keypairs(self, tx, keypairs, password):
+        # first check the provided password
+        seed = self.get_seed(password)
+
         for txin in tx.inputs:
+            x_pubkeys = txin['x_pubkeys']
             address = txin['address']
-            if not self.is_mine(address):
-                continue
-            private_keys = self.get_private_key(address, password)
-            for sec in private_keys:
-                pubkey = public_key_from_private_key(sec)
-                keypairs[ pubkey ] = sec
 
-                # this is needed because we don't store imported pubkeys
-                if address in self.imported_keys.keys():
-                    txin['redeemPubkey'] = pubkey
+            if self.is_mine(address):
 
+                private_keys = self.get_private_key(address, password)
+                for sec in private_keys:
+                    pubkey = public_key_from_private_key(sec)
+                    keypairs[ pubkey ] = sec
 
-    def add_keypairs_from_KeyID(self, tx, keypairs, password):
-        # first check the provided password
-        seed = self.get_seed(password)
+            else:
 
-        for txin in tx.inputs:
-            keyid = txin.get('KeyID')
-            if keyid:
-                roots = []
-                for s in keyid.split('&'):
-                    m = re.match("bip32\((.*),(/\d+/\d+)\)", s)
-                    if not m: continue
-                    xpub = m.group(1)
-                    sequence = m.group(2)
-                    root = self.find_root_by_master_key(xpub)
-                    if not root: continue
-                    sequence = map(lambda x:int(x), sequence.strip('/').split('/'))
-                    root = root + '%d'%sequence[0]
-                    sequence = sequence[1:]
-                    roots.append((root,sequence)) 
-
-                account_id = " & ".join( map(lambda x:x[0], roots) )
-                account = self.accounts.get(account_id)
-                if not account: continue
-                addr = account.get_address(*sequence)
-                txin['address'] = addr # fixme: side effect
-                pk = self.get_private_key(addr, password)
-                for sec in pk:
-                    pubkey = public_key_from_private_key(sec)
-                    keypairs[pubkey] = sec
+                from account import BIP32_Account, OldAccount
+                for x_pubkey in x_pubkeys:
+                    if not is_extended_pubkey(x_pubkey):
+                        continue
+
+                    if x_pubkey[0:2] == 'ff':
+                        xpub, sequence = BIP32_Account.parse_xpubkey(x_pubkey)
+                    elif x_pubkey[0:2] == 'fe':
+                        xpub, sequence = OldAccount.parse_xpubkey(x_pubkey)
 
+                    # look for account that can sign
+                    for k, account in self.accounts.items():
+                        if xpub in account.get_master_pubkeys():
+                            break
+                    else:
+                        continue
 
+                    addr = account.get_address(*sequence)
+                    assert txin['address'] == addr
+                    pk = self.get_private_key(addr, password)
+                    for sec in pk:
+                        pubkey = public_key_from_private_key(sec)
+                        keypairs[pubkey] = sec
 
-    def signrawtransaction(self, tx, input_info, private_keys, password):
 
-        # check that the password is correct
-        seed = self.get_seed(password)
 
-        # if input_info is not known, build it using wallet UTXOs
-        if not input_info:
-            input_info = []
-            unspent_coins = self.get_unspent_coins()
-            for txin in tx.inputs:
-                for item in unspent_coins:
-                    if txin['prevout_hash'] == item['prevout_hash'] and txin['prevout_n'] == item['prevout_n']:
-                        info = { 'address':item['address'], 'scriptPubKey':item['scriptPubKey'] }
-                        self.add_input_info(info)
-                        input_info.append(info)
-                        break
-                else:
-                    print_error( "input not in UTXOs" )
-                    input_info.append(None)
 
-        # add input_info to the transaction
-        print_error("input_info", input_info)
-        tx.add_input_info(input_info)
+    def signrawtransaction(self, tx, private_keys, password):
+
+        # check that the password is correct
+        seed = self.get_seed(password)
 
         # build a list of public/private keys
         keypairs = {}
@@ -480,10 +449,9 @@ class Abstract_Wallet:
             pubkey = public_key_from_private_key(sec)
             keypairs[ pubkey ] = sec
 
-        # add private_keys from KeyID
-        self.add_keypairs_from_KeyID(tx, keypairs, password)
-        # add private keys from wallet
-        self.add_keypairs_from_wallet(tx, keypairs, password)
+        # add private_keys
+        self.add_keypairs(tx, keypairs, password)
+
         # sign the transaction
         self.sign_transaction(tx, keypairs, password)
 
@@ -504,7 +472,7 @@ class Abstract_Wallet:
         secret = keys[0]
         ec = regenerate_key(secret)
         decrypted = ec.decrypt_message(message)
-        return decrypted[0]
+        return decrypted
 
 
 
@@ -673,17 +641,18 @@ class Abstract_Wallet:
         return [x[1] for x in coins]
 
 
-    def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None ):
+    def choose_tx_inputs( self, amount, fixed_fee, num_outputs, domain = None, coins = None ):
         """ todo: minimize tx size """
         total = 0
         fee = self.fee if fixed_fee is None else fixed_fee
-        if domain is None:
-            domain = self.addresses(True)
 
-        for i in self.frozen_addresses:
-            if i in domain: domain.remove(i)
+        if not coins:
+            if domain is None:
+                domain = self.addresses(True)
+            for i in self.frozen_addresses:
+                if i in domain: domain.remove(i)
+            coins = self.get_unspent_coins(domain)
 
-        coins = self.get_unspent_coins(domain)
         inputs = []
 
         for item in coins:
@@ -722,7 +691,7 @@ class Abstract_Wallet:
                 address = inputs[0].get('address')
                 account, _ = self.get_address_index(address)
 
-                if not self.use_change or account == -1:
+                if not self.use_change or account == IMPORTED_ACCOUNT:
                     change_addr = inputs[-1]['address']
                 else:
                     change_addr = self.accounts[account].get_addresses(1)[-self.gap_limit_for_change]
@@ -864,11 +833,11 @@ class Abstract_Wallet:
         return default_label
 
 
-    def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None ):
+    def make_unsigned_transaction(self, outputs, fee=None, change_addr=None, domain=None, coins=None ):
         for address, x in outputs:
             assert is_valid(address), "Address " + address + " is invalid!"
         amount = sum( map(lambda x:x[1], outputs) )
-        inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain )
+        inputs, total, fee = self.choose_tx_inputs( amount, fee, len(outputs), domain, coins )
         if not inputs:
             raise ValueError("Not enough funds")
         for txin in inputs:
@@ -877,10 +846,10 @@ class Abstract_Wallet:
         return Transaction.from_io(inputs, outputs)
 
 
-    def mktx(self, outputs, password, fee=None, change_addr=None, domain= None ):
-        tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain)
+    def mktx(self, outputs, password, fee=None, change_addr=None, domain= None, coins = None ):
+        tx = self.make_unsigned_transaction(outputs, fee, change_addr, domain, coins)
         keypairs = {}
-        self.add_keypairs_from_wallet(tx, keypairs, password)
+        self.add_keypairs(tx, keypairs, password)
         if keypairs:
             self.sign_transaction(tx, keypairs, password)
         return tx
@@ -888,16 +857,19 @@ class Abstract_Wallet:
 
     def add_input_info(self, txin):
         address = txin['address']
-        if address in self.imported_keys.keys():
-            return
         account_id, sequence = self.get_address_index(address)
         account = self.accounts[account_id]
-        txin['KeyID'] = account.get_keyID(sequence)
         redeemScript = account.redeem_script(sequence)
+        txin['x_pubkeys'] = account.get_xpubkeys(sequence)
+        txin['pubkeys'] = pubkeys = account.get_pubkeys(sequence)
+        txin['signatures'] = [None] * len(pubkeys)
+
         if redeemScript: 
             txin['redeemScript'] = redeemScript
+            txin['num_sig'] = 2
         else:
             txin['redeemPubkey'] = account.get_pubkey(*sequence)
+            txin['num_sig'] = 1
 
 
     def sign_transaction(self, tx, keypairs, password):
@@ -938,12 +910,10 @@ class Abstract_Wallet:
             self.seed = pw_encode( decoded, new_password)
             self.storage.put('seed', self.seed, True)
 
-        for k in self.imported_keys.keys():
-            a = self.imported_keys[k]
-            b = pw_decode(a, old_password)
-            c = pw_encode(b, new_password)
-            self.imported_keys[k] = c
-        self.storage.put('imported_keys', self.imported_keys, True)
+        imported_account = self.accounts.get(IMPORTED_ACCOUNT)
+        if imported_account: 
+            imported_account.update_password(old_password, new_password)
+            self.save_accounts()
 
         for k, v in self.master_private_keys.items():
             b = pw_decode(v, old_password)
@@ -1094,15 +1064,35 @@ class Abstract_Wallet:
     def get_accounts(self):
         return self.accounts
 
+    def save_accounts(self):
+        d = {}
+        for k, v in self.accounts.items():
+            d[k] = v.dump()
+        self.storage.put('accounts', d, True)
+
+    def can_import(self):
+        return not self.is_watching_only()
+
+    def is_used(self, address):
+        h = self.history.get(address,[])
+        c, u = self.get_addr_balance(address)
+        return len(h), len(h) > 0 and c == -u
+    
 
 class Imported_Wallet(Abstract_Wallet):
 
     def __init__(self, storage):
         Abstract_Wallet.__init__(self, storage)
+        a = self.accounts.get(IMPORTED_ACCOUNT)
+        if not a:
+            self.accounts[IMPORTED_ACCOUNT] = ImportedAccount({'imported':{}})
+        self.storage.put('wallet_type', 'imported', True)
+
 
     def is_watching_only(self):
-        n = self.imported_keys.values()
-        return n == [''] * len(n)
+        acc = self.accounts[IMPORTED_ACCOUNT]
+        n = acc.keypairs.values()
+        return n == [(None, None)] * len(n)
 
     def has_seed(self):
         return False
@@ -1111,13 +1101,11 @@ class Imported_Wallet(Abstract_Wallet):
         return False
 
     def check_password(self, password):
-        if self.imported_keys:
-            k, v = self.imported_keys.items()[0]
-            sec = pw_decode(v, password)
-            address = address_from_private_key(sec)
-            assert address == k
-
+        self.accounts[IMPORTED_ACCOUNT].get_private_key((0,0), self, password)
 
+    def is_used(self, address):
+        h = self.history.get(address,[])
+        return len(h), False
 
 
 class Deterministic_Wallet(Abstract_Wallet):
@@ -1134,9 +1122,6 @@ class Deterministic_Wallet(Abstract_Wallet):
     def is_watching_only(self):
         return not self.has_seed()
 
-    def check_password(self, password):
-        self.get_seed(password)
-
     def add_seed(self, seed, password):
         if self.seed: 
             raise Exception("a seed exists")
@@ -1154,12 +1139,10 @@ class Deterministic_Wallet(Abstract_Wallet):
         self.create_master_keys(password)
 
     def get_seed(self, password):
-        s = pw_decode(self.seed, password)
-        seed = mnemonic_to_seed(s,'').encode('hex')
-        return seed
+        return pw_decode(self.seed, password)
 
     def get_mnemonic(self, password):
-        return pw_decode(self.seed, password)
+        return self.get_seed(password)
         
     def change_gap_limit(self, value):
         if value >= self.gap_limit:
@@ -1321,32 +1304,6 @@ class Deterministic_Wallet(Abstract_Wallet):
         self.save_accounts()
 
 
-    def save_accounts(self):
-        d = {}
-        for k, v in self.accounts.items():
-            d[k] = v.dump()
-        self.storage.put('accounts', d, True)
-
-    
-
-    def load_accounts(self):
-        Abstract_Wallet.load_accounts(self)
-        d = self.storage.get('accounts', {})
-        for k, v in d.items():
-            if k == 0:
-                v['mpk'] = self.storage.get('master_public_key')
-                self.accounts[k] = OldAccount(v)
-            elif v.get('xpub3'):
-                self.accounts[k] = BIP32_Account_2of3(v)
-            elif v.get('xpub2'):
-                self.accounts[k] = BIP32_Account_2of2(v)
-            elif v.get('xpub'):
-                self.accounts[k] = BIP32_Account(v)
-            elif v.get('pending'):
-                self.accounts[k] = PendingAccount(v)
-            else:
-                print_error("cannot load account", v)
-
 
     def account_is_pending(self, k):
         return type(self.accounts.get(k)) == PendingAccount
@@ -1390,6 +1347,10 @@ class NewWallet(Deterministic_Wallet):
         xpriv = pw_decode( k, password)
         return xpriv
 
+    def check_password(self, password):
+        xpriv = self.get_master_private_key( "m/", password )
+        xpub = self.master_public_keys["m/"]
+        assert deserialize_xkey(xpriv)[3] == deserialize_xkey(xpub)[3]
 
     def create_watching_only_wallet(self, xpub):
         self.storage.put('seed_version', self.seed_version, True)
@@ -1428,7 +1389,7 @@ class NewWallet(Deterministic_Wallet):
 
 
     def create_master_keys(self, password):
-        xpriv, xpub = bip32_root(self.get_seed(password))
+        xpriv, xpub = bip32_root(mnemonic_to_seed(self.get_seed(password),'').encode('hex'))
         self.add_master_public_key("m/", xpub)
         self.add_master_private_key("m/", xpriv, password)
 
@@ -1441,7 +1402,12 @@ class NewWallet(Deterministic_Wallet):
 
 
     def num_accounts(self):
-        keys = self.accounts.keys()
+        keys = []
+        for k, v in self.accounts.items():
+            if type(v) != BIP32_Account:
+                continue
+            keys.append(k)
+
         i = 0
         while True:
             account_id = self.account_id(i)
@@ -1500,6 +1466,12 @@ class Wallet_2of2(NewWallet):
         NewWallet.__init__(self, storage)
         self.storage.put('wallet_type', '2of2', True)
 
+    def can_create_accounts(self):
+        return False
+
+    def can_import(self):
+        return False
+
     def create_account(self):
         xpub1 = self.master_public_keys.get("m/")
         xpub2 = self.master_public_keys.get("cold/")
@@ -1544,12 +1516,13 @@ class Wallet_2of3(Wallet_2of2):
         xpub1 = self.master_public_keys.get("m/")
         xpub2 = self.master_public_keys.get("cold/")
         xpub3 = self.master_public_keys.get("remote/")
-        if xpub2 is None:
-            return 'create_2of3_1'
+        # fixme: we use order of creation
+        if xpub2 and xpub1 is None:
+            return 'create_2fa_2'
         if xpub1 is None:
+            return 'create_2of3_1'
+        if xpub2 is None or xpub3 is None:
             return 'create_2of3_2'
-        if xpub3 is None:
-            return 'create_2of3_3'
 
 
 
@@ -1582,7 +1555,7 @@ class OldWallet(Deterministic_Wallet):
 
 
     def create_master_keys(self, password):
-        seed = pw_decode(self.seed, password)
+        seed = self.get_seed(password)
         mpk = OldAccount.mpk_from_seed(seed)
         self.storage.put('master_public_key', mpk, True)
 
@@ -1607,52 +1580,18 @@ class OldWallet(Deterministic_Wallet):
         self.create_account(mpk)
 
     def get_seed(self, password):
-        seed = pw_decode(self.seed, password)
-        self.accounts[0].check_seed(seed)
+        seed = pw_decode(self.seed, password).encode('utf8')
         return seed
 
+    def check_password(self, password):
+        seed = self.get_seed(password)
+        self.accounts[0].check_seed(seed)
+
     def get_mnemonic(self, password):
         import mnemonic
-        s = pw_decode(self.seed, password)
+        s = self.get_seed(password)
         return ' '.join(mnemonic.mn_encode(s))
 
-
-    def add_keypairs_from_KeyID(self, tx, keypairs, password):
-        # first check the provided password
-        seed = self.get_seed(password)
-        for txin in tx.inputs:
-            keyid = txin.get('KeyID')
-            if keyid:
-                m = re.match("old\(([0-9a-f]+),(\d+),(\d+)", keyid)
-                if not m: continue
-                mpk = m.group(1)
-                if mpk != self.storage.get('master_public_key'): continue 
-                for_change = int(m.group(2))
-                num = int(m.group(3))
-                account = self.accounts[0]
-                addr = account.get_address(for_change, num)
-                txin['address'] = addr # fixme: side effect
-                pk = account.get_private_key(seed, (for_change, num))
-                pubkey = public_key_from_private_key(pk)
-                keypairs[pubkey] = pk
-
-
-
-    def get_private_key(self, address, password):
-        if self.is_watching_only():
-            return []
-
-        out = []
-        if address in self.imported_keys.keys():
-            self.check_password(password)
-            out.append( pw_decode( self.imported_keys[address], password ) )
-        else:
-            seed = self.get_seed(password)
-            account_id, sequence = self.get_address_index(address)
-            pk = self.accounts[0].get_private_key(seed, sequence)
-            out.append(pk)
-        return out
-
     def check_pending_accounts(self):
         pass
 
@@ -1674,8 +1613,7 @@ class Wallet(object):
         if storage.get('wallet_type') == '2of3':
             return Wallet_2of3(storage)
 
-        if storage.file_exists and not storage.get('seed'):
-            # wallet made of imported keys
+        if storage.get('wallet_type') == 'imported':
             return Imported_Wallet(storage)
 
 
@@ -1729,6 +1667,8 @@ class Wallet(object):
 
     @classmethod
     def is_address(self, text):
+        if not text:
+            return False
         for x in text.split():
             if not bitcoin.is_address(x):
                 return False
@@ -1736,6 +1676,8 @@ class Wallet(object):
 
     @classmethod
     def is_private_key(self, text):
+        if not text:
+            return False
         for x in text.split():
             if not bitcoin.is_private_key(x):
                 return False
@@ -1754,8 +1696,8 @@ class Wallet(object):
     def from_address(self, text, storage):
         w = Imported_Wallet(storage)
         for x in text.split():
-            w.imported_keys[x] = ''
-        w.storage.put('imported_keys', w.imported_keys, True)
+            w.accounts[IMPORTED_ACCOUNT].add(x, None, None, None)
+        w.save_accounts()
         return w
 
     @classmethod