Exemplo n.º 1
0
 def on_wizard_complete(self, wizard, storage):
     if storage:
         wallet = Wallet(storage)
         wallet.start_network(self.daemon.network)
         self.daemon.add_wallet(wallet)
         self.load_wallet(wallet)
     elif not self.wallet:
         # wizard did not return a wallet; and there is no wallet open atm
         # try to open last saved wallet (potentially start wizard again)
         self.load_wallet_by_name(self.electrum_config.get_wallet_path(), ask_if_wizard=True)
Exemplo n.º 2
0
def make_address_electrum(mnemonic: str,
                          second: str,
                          num: int = 0,
                          script: str = 'p2wpkh',
                          path: str = 'wallet.db',
                          remove: bool = True):
    if electrum is None:
        raise ImportError(
            'Unable to import electrum.  Follow README instructions.')

    if len(second) < MIN_LEN_PASSWORD:
        raise ValueError(
            f'Password too short {len(second)} < {MIN_LEN_PASSWORD}')
    script_types = ('p2pkh', 'p2wpkh', 'p2wpkh-p2sh')
    if script not in script_types:
        raise ValueError(f'Script {script} must be noe of {script_types}')

    if os.path.exists(path):
        os.unlink(path)

    language = 'english'
    seed = Mnemonic(language).to_seed(mnemonic).hex()

    derivation = None
    if script == 'p2wpkh':
        derivation = "m/84'/0'/0'"
    elif script == 'p2wpkh-p2sh':
        derivation = "m/49'/0'/0'"
    elif script == 'p2pkh':
        script = 'standard'
        derivation = "m/44'/0'/0'"

    ks = keystore.from_bip39_seed(mnemonic, second, derivation, xtype=script)

    db = WalletDB('', manual_upgrades=False)
    db.put('keystore', ks.dump())
    db.put('wallet_type', 'standard')

    storage = WalletStorage(path)
    wallet = Wallet(db, storage, config=SimpleConfig())
    if not storage.file_exists():
        wallet.update_password(old_pw=None,
                               new_pw=second,
                               encrypt_storage=True)
    wallet.synchronize()
    wallet.save_db()

    addr = wallet.get_receiving_addresses()[num]
    wif = wallet.export_private_key(addr, password=second)

    if remove:
        os.unlink(path)

    return AddressResult(address=addr, wif=wif, num=num)
Exemplo n.º 3
0
    def test_update_password_with_app_restarts(self):
        wallet_str = '{"addr_history":{"1364Js2VG66BwRdkaoxAaFtdPb1eQgn8Dr":[],"15CyDgLffJsJgQrhcyooFH4gnVDG82pUrA":[],"1Exet2BhHsFxKTwhnfdsBMkPYLGvobxuW6":[]},"addresses":{"change":[],"receiving":["1364Js2VG66BwRdkaoxAaFtdPb1eQgn8Dr","1Exet2BhHsFxKTwhnfdsBMkPYLGvobxuW6","15CyDgLffJsJgQrhcyooFH4gnVDG82pUrA"]},"keystore":{"keypairs":{"0344b1588589958b0bcab03435061539e9bcf54677c104904044e4f8901f4ebdf5":"L2sED74axVXC4H8szBJ4rQJrkfem7UMc6usLCPUoEWxDCFGUaGUM","0389508c13999d08ffae0f434a085f4185922d64765c0bff2f66e36ad7f745cc5f":"L3Gi6EQLvYw8gEEUckmqawkevfj9s8hxoQDFveQJGZHTfyWnbk1U","04575f52b82f159fa649d2a4c353eb7435f30206f0a6cb9674fbd659f45082c37d559ffd19bea9c0d3b7dcc07a7b79f4cffb76026d5d4dff35341efe99056e22d2":"5JyVyXU1LiRXATvRTQvR9Kp8Rx1X84j2x49iGkjSsXipydtByUq"},"type":"imported"},"pruned_txo":{},"seed_version":13,"stored_height":-1,"transactions":{},"tx_fees":{},"txi":{},"txo":{},"use_encryption":false,"verified_tx3":{},"wallet_type":"standard","winpos-qt":[100,100,840,405]}'
        db = WalletDB(wallet_str, manual_upgrades=False)
        storage = WalletStorage(self.wallet_path)
        wallet = Wallet(db, storage, config=self.config)
        wallet.stop()

        storage = WalletStorage(self.wallet_path)
        # if storage.is_encrypted():
        #     storage.decrypt(password)
        db = WalletDB(storage.read(), manual_upgrades=False)
        wallet = Wallet(db, storage, config=self.config)

        wallet.check_password(None)

        wallet.update_password(None, "1234")
        with self.assertRaises(InvalidPassword):
            wallet.check_password(None)
        with self.assertRaises(InvalidPassword):
            wallet.check_password("wrong password")
        wallet.check_password("1234")
Exemplo n.º 4
0
    def run_and_get_wallet(self):
        # Show network dialog if config does not exist
        if self.network:
            if self.config.get('auto_connect') is None:
                self.choose_server(self.network)

        path = self.storage.path
        if self.storage.requires_split():
            self.hide()
            msg = _(
                "The wallet '%s' contains multiple accounts, which are no longer supported in Electrum 2.7.\n\n"
                "Do you want to split your wallet into multiple files?" % path)
            if not self.question(msg):
                return
            file_list = '\n'.join(self.storage.split_accounts())
            msg = _('Your accounts have been moved to'
                    ) + ':\n' + file_list + '\n\n' + _(
                        'Do you want to delete the old file') + ':\n' + path
            if self.question(msg):
                os.remove(path)
                self.show_warning(_('The file was removed'))
            return

        if self.storage.requires_upgrade():
            self.hide()
            msg = _(
                "The format of your wallet '%s' must be upgraded for Electrum. This change will not be backward compatible"
                % path)
            if not self.question(msg):
                return
            self.storage.upgrade()
            self.show_warning(_('Your wallet was upgraded successfully'))
            self.wallet = Wallet(self.storage)
            self.terminate()
            return self.wallet

        action = self.storage.get_action()
        if action and action != 'new':
            self.hide()
            msg = _("The file '%s' contains an incompletely created wallet.\n"
                    "Do you want to complete its creation now?") % path
            if not self.question(msg):
                if self.question(_("Do you want to delete '%s'?") % path):
                    os.remove(path)
                    self.show_warning(_('The file was removed'))
                return
            self.show()
        if action:
            # self.wallet is set in run
            self.run(action)
            return self.wallet
Exemplo n.º 5
0
 def __init__(self, config, network):
     self.network = network
     self.config = config
     storage = WalletStorage(self.config.get_wallet_path())
     if not storage.file_exists:
         raise BaseException("Wallet not found")
     self.wallet = Wallet(storage)
     self.cmd_runner = Commands(self.config, self.wallet, self.network)
     host = config.get('rpchost', 'localhost')
     port = config.get('rpcport', 7777)
     self.server = SimpleJSONRPCServer((host, port), requestHandler=RequestHandler)
     self.server.socket.settimeout(1)
     for cmdname in known_commands:
         self.server.register_function(getattr(self.cmd_runner, cmdname), cmdname)
Exemplo n.º 6
0
    def test_update_password_of_standard_wallet(self):
        wallet_str = '''{"addr_history":{"12ECgkzK6gHouKAZ7QiooYBuk1CgJLJxes":[],"12iR43FPb5M7sw4Mcrr5y1nHKepg9EtZP1":[],"13HT1pfWctsSXVFzF76uYuVdQvcAQ2MAgB":[],"13kG9WH9JqS7hyCcVL1ssLdNv4aXocQY9c":[],"14Tf3qiiHJXStSU4KmienAhHfHq7FHpBpz":[],"14gmBxYV97mzYwWdJSJ3MTLbTHVegaKrcA":[],"15FGuHvRssu1r8fCw98vrbpfc3M4xs5FAV":[],"17oJzweA2gn6SDjsKgA9vUD5ocT1sSnr2Z":[],"18hNcSjZzRcRP6J2bfFRxp9UfpMoC4hGTv":[],"18n9PFxBjmKCGhd4PCDEEqYsi2CsnEfn2B":[],"19a98ZfEezDNbCwidVigV5PAJwrR2kw4Jz":[],"19z3j2ELqbg2pR87byCCt3BCyKR7rc3q8G":[],"1A3XSmvLQvePmvm7yctsGkBMX9ZKKXLrVq":[],"1CmhFe2BN1h9jheFpJf4v39XNPj8F9U6d":[],"1DuphhHUayKzbkdvjVjf5dtjn2ACkz4zEs":[],"1E4ygSNJpWL2uPXZHBptmU2LqwZTqb1Ado":[],"1GTDSjkVc9vaaBBBGNVqTANHJBcoT5VW9z":[],"1GWqgpThAuSq3tDg6uCoLQxPXQNnU8jZ52":[],"1GhmpwqSF5cqNgdr9oJMZx8dKxPRo4pYPP":[],"1J5TTUQKhwehEACw6Jjte1E22FVrbeDmpv":[],"1JWySzjzJhsETUUcqVZHuvQLA7pfFfmesb":[],"1KQHxcy3QUHAWMHKUtJjqD9cMKXcY2RTwZ":[],"1KoxZfc2KsgovjGDxwqanbFEA76uxgYH4G":[],"1KqVEPXdpbYvEbwsZcEKkrA4A2jsgj9hYN":[],"1N16yDSYe76c5A3CoVoWAKxHeAUc8Jhf9J":[],"1Pm8JBhzUJDqeQQKrmnop1Frr4phe1jbTt":[]},"addresses":{"change":["1GhmpwqSF5cqNgdr9oJMZx8dKxPRo4pYPP","1GTDSjkVc9vaaBBBGNVqTANHJBcoT5VW9z","15FGuHvRssu1r8fCw98vrbpfc3M4xs5FAV","1A3XSmvLQvePmvm7yctsGkBMX9ZKKXLrVq","19z3j2ELqbg2pR87byCCt3BCyKR7rc3q8G","1JWySzjzJhsETUUcqVZHuvQLA7pfFfmesb"],"receiving":["14gmBxYV97mzYwWdJSJ3MTLbTHVegaKrcA","13HT1pfWctsSXVFzF76uYuVdQvcAQ2MAgB","19a98ZfEezDNbCwidVigV5PAJwrR2kw4Jz","1J5TTUQKhwehEACw6Jjte1E22FVrbeDmpv","1Pm8JBhzUJDqeQQKrmnop1Frr4phe1jbTt","13kG9WH9JqS7hyCcVL1ssLdNv4aXocQY9c","1KQHxcy3QUHAWMHKUtJjqD9cMKXcY2RTwZ","12ECgkzK6gHouKAZ7QiooYBuk1CgJLJxes","12iR43FPb5M7sw4Mcrr5y1nHKepg9EtZP1","14Tf3qiiHJXStSU4KmienAhHfHq7FHpBpz","1KqVEPXdpbYvEbwsZcEKkrA4A2jsgj9hYN","17oJzweA2gn6SDjsKgA9vUD5ocT1sSnr2Z","1E4ygSNJpWL2uPXZHBptmU2LqwZTqb1Ado","18hNcSjZzRcRP6J2bfFRxp9UfpMoC4hGTv","1KoxZfc2KsgovjGDxwqanbFEA76uxgYH4G","18n9PFxBjmKCGhd4PCDEEqYsi2CsnEfn2B","1CmhFe2BN1h9jheFpJf4v39XNPj8F9U6d","1DuphhHUayKzbkdvjVjf5dtjn2ACkz4zEs","1GWqgpThAuSq3tDg6uCoLQxPXQNnU8jZ52","1N16yDSYe76c5A3CoVoWAKxHeAUc8Jhf9J"]},"keystore":{"seed":"cereal wise two govern top pet frog nut rule sketch bundle logic","type":"bip32","xprv":"xprv9s21ZrQH143K29XjRjUs6MnDB9wXjXbJP2kG1fnRk8zjdDYWqVkQYUqaDtgZp5zPSrH5PZQJs8sU25HrUgT1WdgsPU8GbifKurtMYg37d4v","xpub":"xpub661MyMwAqRbcEdcCXm1sTViwjBn28zK9kFfrp4C3JUXiW1sfP34f6HA45B9yr7EH5XGzWuTfMTdqpt9XPrVQVUdgiYb5NW9m8ij1FSZgGBF"},"pruned_txo":{},"seed_type":"standard","seed_version":13,"stored_height":-1,"transactions":{},"tx_fees":{},"txi":{},"txo":{},"use_encryption":false,"verified_tx3":{},"wallet_type":"standard","winpos-qt":[619,310,840,405]}'''
        db = WalletDB(wallet_str, manual_upgrades=False)
        storage = WalletStorage(self.wallet_path)
        wallet = Wallet(db, storage, config=self.config)

        wallet.check_password(None)

        wallet.update_password(None, "1234")
        with self.assertRaises(InvalidPassword):
            wallet.check_password(None)
        with self.assertRaises(InvalidPassword):
            wallet.check_password("wrong password")
        wallet.check_password("1234")
Exemplo n.º 7
0
    def __init__(self, config: 'SimpleConfig', daemon: 'Daemon', plugins: 'Plugins'):

        self.config = config
        self.network = daemon.network
        storage = WalletStorage(config.get_wallet_path())
        if not storage.file_exists():
            print("Wallet not found. try 'electrum create'")
            exit()
        if storage.is_encrypted():
            password = getpass.getpass('Password:'******'')
        self.encoding = locale.getpreferredencoding()

        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
        curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
        self.stdscr.keypad(1)
        self.stdscr.border(0)
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        self.set_cursor(0)
        self.w = curses.newwin(10, 50, 5, 5)

        console_stderr_handler.setLevel(logging.CRITICAL)
        self.tab = 0
        self.pos = 0
        self.popup_pos = 0

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""
        self.history = None
        self.txid = []

        util.register_callback(self.update, ['wallet_updated', 'network_updated'])

        self.tab_names = [_("History"), _("Send"), _("Receive"), _("Addresses"), _("Contacts"), _("Banner")]
        self.num_tabs = len(self.tab_names)
Exemplo n.º 8
0
    def __init__(self, config, daemon, plugins):

        self.config = config
        self.network = daemon.network
        storage = WalletStorage(config.get_wallet_path())
        if not storage.file_exists():
            print("Wallet not found. try 'electrum create'")
            exit()
        if storage.is_encrypted():
            password = getpass.getpass('Password:'******'')
        self.encoding = locale.getpreferredencoding()

        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
        curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
        self.stdscr.keypad(1)
        self.stdscr.border(0)
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        self.set_cursor(0)
        self.w = curses.newwin(10, 50, 5, 5)

        set_verbosity(False)
        self.tab = 0
        self.pos = 0
        self.popup_pos = 0

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""
        self.history = None

        if self.network:
            self.network.register_callback(self.update, ['updated'])

        self.tab_names = [_("History"), _("Send"), _("Receive"), _("Addresses"), _("Contacts"), _("Banner")]
        self.num_tabs = len(self.tab_names)
Exemplo n.º 9
0
 def on_restore_pw(self, wizard, seed, password):
     # FIXME
     # wallet.add_seed(seed, password)
     storage = wizard.storage
     words = seed.split()
     n = len(words) / 2
     keystore1 = keystore.xprv_from_seed(' '.join(words[0:n]), password)
     keystore2 = keystore.xprv_from_seed(' '.join(words[n:]), password)
     keystore1.save(storage, 'x1/')
     keystore2.save(storage, 'x2/')
     long_user_id, short_id = get_user_id(storage)
     xpub3 = make_xpub(signing_xpub, long_user_id)
     keystore3 = keystore.from_xpub(xpub3)
     keystore3.save(storage, 'x3/')
     wizard.wallet = Wallet(storage)
     wizard.create_addresses()
Exemplo n.º 10
0
def load_wallet(xpub):
    if xpub in wallets:
        return wallets[xpub]
    config = SimpleConfig()
    command_runner = Commands(config, wallet=None, network=network)
    # get wallet on disk
    wallet_dir = os.path.dirname(config.get_wallet_path())
    wallet_path = os.path.join(wallet_dir, xpub)
    if not os.path.exists(wallet_path):
        config.set_key('wallet_path', wallet_path)
        command_runner.restore(xpub)
    storage = WalletStorage(wallet_path)
    wallet = Wallet(storage)
    wallet.start_network(network)
    command_runner.wallet = wallet
    wallets[xpub] = command_runner
    return command_runner
Exemplo n.º 11
0
def run_offline_command(config, config_options, plugins):
    print(config)
    print(config_options)
    print(plugins)
    cmdname = config.get('cmd')
    cmd = known_commands[cmdname]
    print(cmd.__dict__)
    password = config_options.get('password')
    if cmd.requires_wallet:
        storage = WalletStorage(config.get_wallet_path())
        if storage.is_encrypted():
            if storage.is_encrypted_with_hw_device():
                password = get_password_for_hw_device_encrypted_storage(
                    plugins)
                config_options['password'] = password
            storage.decrypt(password)
        wallet = Wallet(storage)
    else:
        wallet = None
    # check password
    if cmd.requires_password and wallet.has_password():
        try:
            wallet.check_password(password)
        except InvalidPassword:
            print_msg("Error: This password does not decode this wallet.")
            sys.exit(1)
    if cmd.requires_network:
        print_msg("Warning: running command offline")
    # arguments passed to function
    args = [config.get(x) for x in cmd.params]
    # decode json arguments
    if cmdname not in ('setconfig', ):
        args = list(map(json_decode, args))
    # options
    kwargs = {}
    for x in cmd.options:
        kwargs[x] = (config_options.get(x)
                     if x in ['password', 'new_password'] else config.get(x))
    cmd_runner = Commands(config, wallet, None)
    func = getattr(cmd_runner, cmd.name)
    result = func(*args, **kwargs)
    # save wallet
    if wallet:
        wallet.storage.write()
    return result
Exemplo n.º 12
0
 def start(self):
     self.logger.info("start")
     user_config = {
         "auto_connect": False,
         "oneserver": True,
         "server": "localhost:" + str(self.electrumx.tcp_port) + ":t",
         "request_initial_sync": False,
         "lightning_listen": "127.0.0.1:" + str(self.port),
     }
     config = simple_config.SimpleConfig(
         user_config, read_user_dir_function=lambda: self.directory)
     constants.set_regtest()
     self.actual = Daemon(config)
     assert self.actual.network.asyncio_loop.is_running()
     wallet_path = self.actual.cmd_runner.create(segwit=True)['path']
     storage = WalletStorage(wallet_path)
     wallet = Wallet(storage)
     wallet.start_network(self.actual.network)
     self.actual.add_wallet(wallet)
Exemplo n.º 13
0
 def create_remote_key(self, wizard):
     email = self.accept_terms_of_use(wizard)
     mpk = wizard.storage.get('master_public_keys')
     xpub1 = mpk["x1/"]
     xpub2 = mpk["x2/"]
     # Generate third key deterministically.
     long_user_id, short_id = get_user_id(wizard.storage)
     xpub3 = make_xpub(signing_xpub, long_user_id)
     # secret must be sent by the server
     try:
         r = server.create(xpub1, xpub2, email)
     except socket.error:
         wizard.show_message('Server not reachable, aborting')
         return
     except TrustedCoinException as e:
         if e.status_code == 409:
             r = None
         else:
             raise e
     if r is None:
         otp_secret = None
     else:
         otp_secret = r.get('otp_secret')
         if not otp_secret:
             wizard.show_message(_('Error'))
             return
         _xpub3 = r['xpubkey_cosigner']
         _id = r['id']
         try:
             assert _id == short_id, ("user id error", _id, short_id)
             assert xpub3 == _xpub3, ("xpub3 error", xpub3, _xpub3)
         except Exception as e:
             wizard.show_message(str(e))
             return
     if not self.setup_google_auth(wizard, short_id, otp_secret):
         wizard.show_message("otp error")
         return
     keystore3 = keystore.from_xpub(xpub3)
     keystore3.save(wizard.storage, 'x3/')
     wizard.storage.put('use_trustedcoin', True)
     wizard.storage.write()
     wizard.wallet = Wallet(wizard.storage)
     wizard.run('create_addresses')
Exemplo n.º 14
0
 def load_wallet(self, path, password):
     # wizard will be launched if we return
     if path in self.wallets:
         wallet = self.wallets[path]
         return wallet
     storage = WalletStorage(path, manual_upgrades=True)
     if not storage.file_exists():
         return
     if storage.is_encrypted():
         if not password:
             return
         storage.decrypt(password)
     if storage.requires_split():
         return
     if storage.get_action():
         return
     wallet = Wallet(storage)
     wallet.start_threads(self.network)
     self.wallets[path] = wallet
     return wallet
Exemplo n.º 15
0
    def __init__(self, config, network):
        self.network = network
        self.config = config
        storage = WalletStorage(config.get_wallet_path())
        if not storage.file_exists:
            print "Wallet not found. try 'electrum create'"
            exit()

        self.done = 0
        self.last_balance = ""

        set_verbosity(False)

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""

        self.wallet = Wallet(storage)
        self.wallet.start_threads(network)
        self.contacts = StoreDict(self.config, 'contacts')

        self.wallet.network.register_callback('updated', self.updated)
        self.wallet.network.register_callback('connected', self.connected)
        self.wallet.network.register_callback('disconnected',
                                              self.disconnected)
        self.wallet.network.register_callback('disconnecting',
                                              self.disconnecting)
        self.wallet.network.register_callback('peers', self.peers)
        self.wallet.network.register_callback('banner', self.print_banner)
        self.commands = [_("[h] - displays this help text"), \
                         _("[i] - display transaction history"), \
                         _("[o] - enter payment order"), \
                         _("[p] - print stored payment order"), \
                         _("[s] - send stored payment order"), \
                         _("[r] - show own receipt addresses"), \
                         _("[c] - display contacts"), \
                         _("[b] - print server banner"), \
                         _("[q] - quit") ]
        self.num_commands = len(self.commands)
Exemplo n.º 16
0
    def run_and_get_wallet(self):
        path = self.storage.path
        if self.storage.requires_split():
            self.hide()
            msg = _(
                "The wallet '{}' contains multiple accounts, which are no longer supported since Electrum 2.7.\n\n"
                "Do you want to split your wallet into multiple files?"
            ).format(path)
            if not self.question(msg):
                return
            file_list = '\n'.join(self.storage.split_accounts())
            msg = _('Your accounts have been moved to'
                    ) + ':\n' + file_list + '\n\n' + _(
                        'Do you want to delete the old file') + ':\n' + path
            if self.question(msg):
                os.remove(path)
                self.show_warning(_('The file was removed'))
            return

        action = self.storage.get_action()
        if action and action not in ('new', 'upgrade_storage'):
            self.hide()
            msg = _("The file '{}' contains an incompletely created wallet.\n"
                    "Do you want to complete its creation now?").format(path)
            if not self.question(msg):
                if self.question(
                        _("Do you want to delete '{}'?").format(path)):
                    os.remove(path)
                    self.show_warning(_('The file was removed'))
                return
            self.show()
        if action:
            # self.wallet is set in run
            self.run(action)
            return self.wallet

        self.wallet = Wallet(self.storage)
        return self.wallet
Exemplo n.º 17
0
 def init_storage_from_path(self, path):
     self.storage = WalletStorage(path)
     self.basename = self.storage.basename()
     if not self.storage.file_exists():
         self.require_password = False
         self.message = _('Press Next to create')
     elif self.storage.is_encrypted():
         if not self.storage.is_encrypted_with_user_pw():
             raise Exception(
                 "Kivy GUI does not support this type of encrypted wallet files."
             )
         self.require_password = True
         self.pw_check = self.storage.check_password
         self.message = self.enter_pw_message
     else:
         # it is a bit wasteful load the wallet here and load it again in main_window,
         # but that is fine, because we are progressively enforcing storage encryption.
         db = WalletDB(self.storage.read(), manual_upgrades=False)
         wallet = Wallet(db, self.storage, config=self.app.electrum_config)
         self.require_password = wallet.has_password()
         self.pw_check = wallet.check_password
         self.message = self.enter_pw_message if self.require_password else _(
             'Wallet not encrypted')
Exemplo n.º 18
0
 def _start_wizard_to_select_or_create_wallet(self, path) -> Optional[Abstract_Wallet]:
     wizard = InstallWizard(self.config, self.app, self.plugins)
     try:
         path, storage = wizard.select_storage(path, self.daemon.get_wallet)
         # storage is None if file does not exist
         if storage is None:
             wizard.path = path  # needed by trustedcoin plugin
             wizard.run('new')
             storage = wizard.create_storage(path)
         else:
             wizard.run_upgrades(storage)
     except (UserCancelled, GoBack):
         return
     except WalletAlreadyOpenInMemory as e:
         return e.wallet
     finally:
         wizard.terminate()
     # return if wallet creation is not complete
     if storage is None or storage.get_action():
         return
     wallet = Wallet(storage)
     wallet.start_network(self.daemon.network)
     self.daemon.add_wallet(wallet)
     return wallet
Exemplo n.º 19
0
    def start_new_window(self, path, uri, app_is_starting=False):
        '''Raises the window for the wallet if it is open.  Otherwise
        opens the wallet and creates a new window for it'''
        try:
            wallet = self.daemon.load_wallet(path, None)
        except BaseException as e:
            traceback.print_exc(file=sys.stdout)
            d = QMessageBox(QMessageBox.Warning, _('Error'),
                            _('Cannot load wallet') + ' (1):\n' + str(e))
            d.exec_()
            if app_is_starting:
                # do not return so that the wizard can appear
                wallet = None
            else:
                return
        if not wallet:
            wizard = InstallWizard(self.config, self.app, self.plugins)
            storage = None
            try:
                path, storage = wizard.select_storage(path,
                                                      self.daemon.get_wallet)
                # storage is None if file does not exist
                if storage is None:
                    wizard.path = path  # needed by trustedcoin plugin
                    wizard.run('new')
                    storage = wizard.create_storage(path)
                else:
                    wizard.run_upgrades(storage)
            except UserCancelled:
                return
            except GoBack as e:
                self.print_error(
                    '[start_new_window] Exception caught (GoBack)', e)
            except (WalletFileException, BitcoinException) as e:
                traceback.print_exc(file=sys.stderr)
                d = QMessageBox(QMessageBox.Warning, _('Error'),
                                _('Cannot load wallet') + ' (2):\n' + str(e))
                d.exec_()
                return
            finally:
                wizard.terminate()
            # return if wallet creation is not complete
            if storage is None or storage.get_action():
                return
            wallet = Wallet(storage)
            if not self.daemon.get_wallet(wallet.storage.path):
                # wallet was not in memory
                wallet.start_network(self.daemon.network)
                self.daemon.add_wallet(wallet)
        try:
            for w in self.windows:
                if w.wallet.storage.path == wallet.storage.path:
                    break
            else:
                w = self.create_window_for_wallet(wallet)
        except BaseException as e:
            traceback.print_exc(file=sys.stdout)
            d = QMessageBox(
                QMessageBox.Warning, _('Error'),
                _('Cannot create window for wallet') + ':\n' + str(e))
            d.exec_()
            if app_is_starting:
                wallet_dir = os.path.dirname(path)
                path = os.path.join(wallet_dir,
                                    get_new_wallet_name(wallet_dir))
                self.start_new_window(path, uri)
            return
        if uri:
            w.pay_to_URI(uri)
        w.bring_to_top()
        w.setWindowState(w.windowState() & ~QtCore.Qt.WindowMinimized
                         | QtCore.Qt.WindowActive)

        # this will activate the window
        w.activateWindow()
        return w
Exemplo n.º 20
0
 def restore_hardware_wallet(self):
     self.storage.put('wallet_type', self.wallet_type)
     self.wallet = Wallet(self.storage)
     self.wallet.plugin.on_restore_wallet(self.wallet, self)
     self.terminate()
 def _sanity_check_upgraded_db(self, db):
     self.assertFalse(db.requires_split())
     self.assertFalse(db.requires_upgrade())
     w = Wallet(db, None, config=self.config)
Exemplo n.º 22
0
 def create_2fa(self):
     self.storage.put('wallet_type', '2fa')
     self.wallet = Wallet(self.storage)
     self.run('show_disclaimer')
Exemplo n.º 23
0
 def restore_2fa(self):
     self.storage.put('wallet_type', '2fa')
     self.wallet = Wallet(self.storage)
     self.wallet.plugin.on_restore_wallet(self.wallet, self)
Exemplo n.º 24
0
                print(
                    f"> tested {num_tested} passwords so far... most recently tried: {password!r}"
                )


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("ERROR. usage: bruteforce_pw.py <path_to_wallet_file>")
        sys.exit(1)
    path = sys.argv[1]

    config = SimpleConfig()
    storage = WalletStorage(path)
    if not storage.file_exists():
        print(f"ERROR. wallet file not found at path: {path}")
        sys.exit(1)
    if storage.is_encrypted():
        test_password = partial(test_password_for_storage_encryption, storage)
        print(f"wallet found: with storage encryption.")
    else:
        db = WalletDB(storage.read(), manual_upgrades=True)
        wallet = Wallet(db, storage, config=config)
        if not wallet.has_password():
            print("wallet found but it is not encrypted.")
            sys.exit(0)
        test_password = partial(test_password_for_keystore_encryption, wallet)
        print(f"wallet found: with keystore encryption.")
    password = bruteforce_loop(test_password)
    print(f"====================")
    print(f"password found: {password}")
Exemplo n.º 25
0
 def _sanity_check_upgraded_storage(self, storage):
     self.assertFalse(storage.requires_split())
     self.assertFalse(storage.requires_upgrade())
     w = Wallet(storage)
Exemplo n.º 26
0

config = SimpleConfig({"testnet": True})  # to use ~/.electrum-doi/testnet as datadir
constants.set_testnet()  # to set testnet magic bytes
daemon = Daemon(config, listen_jsonrpc=False)
network = daemon.network
assert network.asyncio_loop.is_running()

# get wallet on disk
wallet_dir = os.path.dirname(config.get_wallet_path())
wallet_path = os.path.join(wallet_dir, "test_wallet")
if not os.path.exists(wallet_path):
    create_new_wallet(path=wallet_path, config=config)

# open wallet
storage = WalletStorage(wallet_path)
wallet = Wallet(storage, config=config)
wallet.start_network(network)

# you can use ~CLI commands by accessing command_runner
command_runner = Commands(config=config, daemon=daemon, network=network)
command_runner.wallet = wallet
print("balance", command_runner.getbalance())
print("addr",    command_runner.getunusedaddress())
print("gettx",   command_runner.gettransaction("bd3a700b2822e10a034d110c11a596ee7481732533eb6aca7f9ca02911c70a4f"))

# but you might as well interact with the underlying methods directly
print("balance", wallet.get_balance())
print("addr",    wallet.get_unused_address())
print("gettx",   network.run_from_another_thread(network.get_transaction("bd3a700b2822e10a034d110c11a596ee7481732533eb6aca7f9ca02911c70a4f")))
Exemplo n.º 27
0
    def run_and_get_wallet(self, get_wallet_from_daemon):

        vbox = QVBoxLayout()

        logo = QLabel()
        if self.config.get('qt_gui_color_theme') == 'dark':
            logo.setPixmap(
                QPixmap(":icons/dgld_wh.png").scaledToWidth(
                    96, mode=Qt.SmoothTransformation))
        else:
            logo.setPixmap(
                QPixmap(":icons/dgld_bl.png").scaledToWidth(
                    96, mode=Qt.SmoothTransformation))
        logo.setMaximumWidth(100)
        vbox.addWidget(logo)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(_('Wallet') + ':'))
        self.name_e = QLineEdit()
        #restrict input to wallet name qlineedit
        regex = QRegExp("[a-z-A-Z0-9_]+")
        validator = QRegExpValidator(regex)
        self.name_e.setValidator(validator)

        hbox.addWidget(self.name_e)
        button = QPushButton(_('Choose...'))
        hbox.addWidget(button)
        vbox.addLayout(hbox)

        self.msg_label = QLabel('')
        vbox.addWidget(self.msg_label)
        hbox2 = QHBoxLayout()
        self.pw_e = QLineEdit('', self)
        self.pw_e.setFixedWidth(150)
        self.pw_e.setEchoMode(2)
        self.pw_label = QLabel(_('Password') + ':')
        hbox2.addWidget(self.pw_label)
        hbox2.addWidget(self.pw_e)
        hbox2.addStretch()
        vbox.addLayout(hbox2)
        self.set_layout(vbox,
                        title=_('Ocean Wallet - ' + constants.net.WALLETTITLE +
                                ' blockchain'))

        wallet_folder = os.path.dirname(self.storage.path)

        def on_choose():
            path, __ = QFileDialog.getOpenFileName(self,
                                                   "Select your wallet file",
                                                   wallet_folder)
            if path:
                self.name_e.setText(path)

        def on_filename(filename):
            path = os.path.join(wallet_folder, filename)
            wallet_from_memory = get_wallet_from_daemon(path)
            try:
                if wallet_from_memory:
                    self.storage = wallet_from_memory.storage
                else:
                    self.storage = WalletStorage(path, manual_upgrades=True)
                self.next_button.setEnabled(True)
            except BaseException:
                traceback.print_exc(file=sys.stderr)
                self.storage = None
                self.next_button.setEnabled(False)
            if self.storage:
                if not self.storage.file_exists():
                    msg =_("This file does not exist.") + '\n' \
                          + _("Press 'Next' to create this wallet, or choose another file.")
                    pw = False
                elif not wallet_from_memory:
                    if self.storage.is_encrypted_with_user_pw():
                        msg = _("This file is encrypted with a password.") + '\n' \
                              + _('Enter your password or choose another file.')
                        pw = True
                    elif self.storage.is_encrypted_with_hw_device():
                        msg = _("This file is encrypted using a hardware device.") + '\n' \
                              + _("Press 'Next' to choose device to decrypt.")
                        pw = False
                    else:
                        msg = _("Press 'Next' to open this wallet.")
                        pw = False
                else:
                    msg = _("This file is already open in memory.") + "\n" \
                        + _("Press 'Next' to create/focus window.")
                    pw = False
            else:
                msg = _('Cannot read file')
                pw = False
            self.msg_label.setText(msg)
            if pw:
                self.pw_label.show()
                self.pw_e.show()
                self.pw_e.setFocus()
            else:
                self.pw_label.hide()
                self.pw_e.hide()

        button.clicked.connect(on_choose)
        self.name_e.textChanged.connect(on_filename)
        n = os.path.basename(self.storage.path)
        self.name_e.setText(n)

        while True:
            if self.loop.exec_() != 2:  # 2 = next
                return
            if self.storage.file_exists() and not self.storage.is_encrypted():
                break
            if not self.storage.file_exists():
                break
            wallet_from_memory = get_wallet_from_daemon(self.storage.path)
            if wallet_from_memory:
                return wallet_from_memory
            if self.storage.file_exists() and self.storage.is_encrypted():
                if self.storage.is_encrypted_with_user_pw():
                    password = self.pw_e.text()
                    try:
                        self.storage.decrypt(password)
                        break
                    except InvalidPassword as e:
                        QMessageBox.information(None, _('Error'), str(e))
                        continue
                    except BaseException as e:
                        traceback.print_exc(file=sys.stdout)
                        QMessageBox.information(None, _('Error'), str(e))
                        return
                elif self.storage.is_encrypted_with_hw_device():
                    try:
                        self.run('choose_hw_device', HWD_SETUP_DECRYPT_WALLET)
                    except InvalidPassword as e:
                        QMessageBox.information(
                            None, _('Error'),
                            _('Failed to decrypt using this hardware device.')
                            + '\n' +
                            _('If you use a passphrase, make sure it is correct.'
                              ))
                        self.stack = []
                        return self.run_and_get_wallet(get_wallet_from_daemon)
                    except BaseException as e:
                        traceback.print_exc(file=sys.stdout)
                        QMessageBox.information(None, _('Error'), str(e))
                        return
                    if self.storage.is_past_initial_decryption():
                        break
                    else:
                        return
                else:
                    raise Exception('Unexpected encryption version')

        path = self.storage.path
        if self.storage.requires_split():
            self.hide()
            msg = _(
                "The wallet '{}' contains multiple accounts, which are not supported.\n\n"
                "Do you want to split your wallet into multiple files?"
            ).format(path)
            if not self.question(msg):
                return
            file_list = '\n'.join(self.storage.split_accounts())
            msg = _('Your accounts have been moved to'
                    ) + ':\n' + file_list + '\n\n' + _(
                        'Do you want to delete the old file') + ':\n' + path
            if self.question(msg):
                os.remove(path)
                self.show_warning(_('The file was removed'))
            return

        action = self.storage.get_action()
        if action and action not in ('new', 'upgrade_storage'):
            self.hide()
            msg = _("The file '{}' contains an incompletely created wallet.\n"
                    "Do you want to complete its creation now?").format(path)
            if not self.question(msg):
                if self.question(
                        _("Do you want to delete '{}'?").format(path)):
                    os.remove(path)
                    self.show_warning(_('The file was removed'))
                return
            self.show()
        if action:
            # self.wallet is set in run
            self.run(action)
            return self.wallet

        self.wallet = Wallet(self.storage, self.config.get('contract_hash'))
        return self.wallet
Exemplo n.º 28
0
 def create_2fa(self):
     print 'create 2fa'
     self.storage.put('wallet_type', '2fa')
     self.wallet = Wallet(self.storage)
     self.run_wallet()
Exemplo n.º 29
0
def run_non_RPC(config):
    cmdname = config.get('cmd')

    storage = WalletStorage(config.get_wallet_path())
    if storage.file_exists():
        sys.exit("Error: Remove the existing wallet first!")

    def password_dialog():
        return prompt_password("Password (hit return if you do not wish to encrypt your wallet):")

    if cmdname == 'restore':
        text = config.get('text').strip()
        passphrase = config.get('passphrase', '')
        password = password_dialog() if keystore.is_private(text) else None
        if keystore.is_address_list(text):
            wallet = Imported_Wallet(storage)
            for x in text.split():
                wallet.import_address(x)
        elif keystore.is_private_key_list(text):
            k = keystore.Imported_KeyStore({})
            storage.put('keystore', k.dump())
            storage.put('use_encryption', bool(password))
            wallet = Imported_Wallet(storage)
            for x in text.split():
                wallet.import_private_key(x, password)
            storage.write()
        else:
            if keystore.is_seed(text):
                k = keystore.from_seed(text, passphrase, False)
            elif keystore.is_master_key(text):
                k = keystore.from_master_key(text)
            else:
                sys.exit("Error: Seed or key not recognized")
            if password:
                k.update_password(None, password)
            storage.put('keystore', k.dump())
            storage.put('wallet_type', 'standard')
            storage.put('use_encryption', bool(password))
            storage.write()
            wallet = Wallet(storage)
        if not config.get('offline'):
            network = Network(config)
            network.start()
            wallet.start_threads(network)
            print_msg("Recovering wallet...")
            wallet.synchronize()
            wallet.wait_until_synchronized()
            wallet.stop_threads()
            # note: we don't wait for SPV
            msg = "Recovery successful" if wallet.is_found() else "Found no history for this wallet"
        else:
            msg = "This wallet was restored offline. It may contain more addresses than displayed."
        print_msg(msg)

    elif cmdname == 'create':
        password = password_dialog()
        passphrase = config.get('passphrase', '')
        seed_type = 'segwit' if config.get('segwit') else 'standard'
        seed = Mnemonic('en').make_seed(seed_type)
        k = keystore.from_seed(seed, passphrase, False)
        storage.put('keystore', k.dump())
        storage.put('wallet_type', 'standard')
        wallet = Wallet(storage)
        wallet.update_password(None, password, True)
        wallet.synchronize()
        print_msg("Your wallet generation seed is:\n\"%s\"" % seed)
        print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")

    wallet.storage.write()
    print_msg("Wallet saved in '%s'" % wallet.storage.path)
    sys.exit(0)
Exemplo n.º 30
0
from electrum.wallet import Wallet


class InMemoryWalletStorage(dict):
    def put(self, key, value, _save):
        self[key] = value


storage = InMemoryWalletStorage()
wallet = Wallet(storage)
# print(wallet)
wallet.synchronize()  # generates addresses up to the gap limit.