示例#1
0
    def __init__(self, config, daemon, plugins):
        self.config = config
        network = daemon.network
        storage = WalletStorage(config.get_wallet_path())
        if not storage.file_exists:
            print "Wallet not found. try 'electrum-ltc 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')

        network.register_callback(self.on_network, ['updated', '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)
示例#2
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
示例#3
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.pw_check = self.storage.check_password
         if self.app.password and self.check_password(self.app.password):
             self.pw = self.app.password  # must be set so that it is returned in callback
             self.require_password = False
             self.message = _('Press Next to open')
         else:
             self.require_password = True
             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')
class ElectrumGui:

    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)

    def main(self):
        self.wallet.start_threads(self.network)
        while True:
            try:
                self.server.handle_request()
            except socket.timeout:
                continue
            except:
                break
        self.wallet.stop_threads()
示例#5
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-ltc 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)

        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)
示例#6
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)
示例#7
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-ltc 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(self.network)
        self.contacts = StoreDict(self.config, 'contacts')

        self.network.register_callback(self.on_network, ['updated', '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)
示例#8
0
 def create_wallet(self, text, password):
     if self.wallet_type == 'standard':
         self.wallet = Wallet.from_text(text, password, self.storage)
         self.run('create_addresses')
     else:
         self.storage.put('wallet_type', self.wallet_type)
         self.wallet = Multisig_Wallet(self.storage)
         self.wallet.add_seed(text, password)
         self.wallet.create_master_keys(password)
         action = self.wallet.get_action()
         self.run(action)
示例#9
0
    def __init__(self, config, network):
        self.network = network
        self.config = config
        storage = WalletStorage(config)
        if not storage.file_exists:
            print "Wallet not found. try 'electrum-ltc 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.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)
示例#10
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)
示例#11
0
    def run_and_get_wallet(self):

        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
示例#12
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
示例#13
0
    def __init__(self, config, network):
        self.network = network
        self.config = config
        storage = WalletStorage(config)
        if not storage.file_exists:
            print "Wallet not found. try 'electrum-ltc 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.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)
示例#14
0
class ElectrumGui:

    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-ltc 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(self.network)
        self.contacts = StoreDict(self.config, 'contacts')

        self.network.register_callback(self.on_network, ['updated', '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)

    def on_network(self, event, *args):
        if event == 'updated':
            self.updated()
        elif event == 'banner':
            self.print_banner()

    def main_command(self):
        self.print_balance()
        c = raw_input("enter command: ")
        if   c == "h" : self.print_commands()
        elif c == "i" : self.print_history()
        elif c == "o" : self.enter_order()
        elif c == "p" : self.print_order()
        elif c == "s" : self.send_order()
        elif c == "r" : self.print_addresses()
        elif c == "c" : self.print_contacts()
        elif c == "b" : self.print_banner()
        elif c == "n" : self.network_dialog()
        elif c == "e" : self.settings_dialog()
        elif c == "q" : self.done = 1
        else: self.print_commands()

    def updated(self):
        s = self.get_balance()
        if s != self.last_balance:
            print(s)
        self.last_balance = s
        return True

    def print_commands(self):
        self.print_list(self.commands, "Available commands")

    def print_history(self):
        width = [20, 40, 14, 14]
        delta = (80 - sum(width) - 4)/3
        format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%" \
        + "%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s"
        b = 0
        messages = []

        for item in self.wallet.get_history():
            tx_hash, confirmations, value, timestamp, balance = item
            if confirmations:
                try:
                    time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
                except Exception:
                    time_str = "unknown"
            else:
                time_str = 'unconfirmed'

            label = self.wallet.get_label(tx_hash)
            messages.append( format_str%( time_str, label, format_satoshis(value, whitespaces=True), format_satoshis(balance, whitespaces=True) ) )

        self.print_list(messages[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance")))


    def print_balance(self):
        print(self.get_balance())

    def get_balance(self):
        if self.wallet.network.is_connected():
            if not self.wallet.up_to_date:
                msg = _( "Synchronizing..." )
            else:
                c, u, x =  self.wallet.get_balance()
                msg = _("Balance")+": %f  "%(Decimal(c) / COIN)
                if u:
                    msg += "  [%f unconfirmed]"%(Decimal(u) / COIN)
                if x:
                    msg += "  [%f unmatured]"%(Decimal(x) / COIN)
        else:
                msg = _( "Not connected" )

        return(msg)


    def print_contacts(self):
        messages = map(lambda x: "%20s   %45s "%(x[0], x[1][1]), self.contacts.items())
        self.print_list(messages, "%19s  %25s "%("Key", "Value"))

    def print_addresses(self):
        messages = map(lambda addr: "%30s    %30s       "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addresses())
        self.print_list(messages, "%19s  %25s "%("Address", "Label"))

    def print_order(self):
        print("send order to " + self.str_recipient + ", amount: " + self.str_amount \
              + "\nfee: " + self.str_fee + ", desc: " + self.str_description)

    def enter_order(self):
        self.str_recipient = raw_input("Pay to: ")
        self.str_description = raw_input("Description : ")
        self.str_amount = raw_input("Amount: ")
        self.str_fee = raw_input("Fee: ")

    def send_order(self):
        self.do_send()

    def print_banner(self):
        for i, x in enumerate( self.wallet.network.banner.split('\n') ):
            print( x )

    def print_list(self, list, firstline):
        self.maxpos = len(list)
        if not self.maxpos: return
        print(firstline)
        for i in range(self.maxpos):
            msg = list[i] if i < len(list) else ""
            print(msg)


    def main(self):
        while self.done == 0: self.main_command()

    def do_send(self):
        if not is_valid(self.str_recipient):
            print(_('Invalid Litecoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            print(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            print(_('Invalid Fee'))
            return

        if self.wallet.use_encryption:
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None

        c = ""
        while c != "y":
            c = raw_input("ok to send (y/n)?")
            if c == "n": return

        try:
            tx = self.wallet.mktx([(TYPE_ADDRESS, self.str_recipient, amount)], password, self.config, fee)
        except Exception as e:
            print(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.hash()] = self.str_description

        print(_("Please wait..."))
        status, msg = self.network.broadcast(tx)

        if status:
            print(_('Payment sent.'))
            #self.do_clear()
            #self.update_contacts_tab()
        else:
            print(_('Error'))

    def network_dialog(self):
        print("use 'electrum-ltc setconfig server/proxy' to change your network settings")
        return True


    def settings_dialog(self):
        print("use 'electrum-ltc setconfig' to change your settings")
        return True

    def password_dialog(self):
        return getpass.getpass()


#   XXX unused

    def run_receive_tab(self, c):
        #if c == 10:
        #    out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"])
        return

    def run_contacts_tab(self, c):
        pass
示例#15
0
 def set_enabled():
     wizard.next_button.setEnabled(Wallet.is_xprv(clean_text(text)))
示例#16
0
 def set_enabled():
     wizard.next_button.setEnabled(
         Wallet.is_xprv(clean_text(text)))
示例#17
0
class ElectrumGui:

    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-ltc 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

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

        self.tab_names = [_("History"), _("Send"), _("Receive"), _("Addresses"), _("Contacts"), _("Banner")]
        self.num_tabs = len(self.tab_names)


    def set_cursor(self, x):
        try:
            curses.curs_set(x)
        except Exception:
            pass

    def restore_or_create(self):
        pass

    def verify_seed(self):
        pass

    def get_string(self, y, x):
        self.set_cursor(1)
        curses.echo()
        self.stdscr.addstr( y, x, " "*20, curses.A_REVERSE)
        s = self.stdscr.getstr(y,x)
        curses.noecho()
        self.set_cursor(0)
        return s

    def update(self, event, *args):
        self.update_history()
        if self.tab == 0:
            self.print_history()
        self.refresh()

    def print_history(self):

        width = [20, 40, 14, 14]
        delta = (self.maxx - sum(width) - 4)/3
        format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%"+"%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s"

        if self.history is None:
            self.update_history()

        self.print_list(self.history[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance")))

    def update_history(self):
        width = [20, 40, 14, 14]
        delta = (self.maxx - sum(width) - 4)/3
        format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%"+"%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s"

        b = 0
        self.history = []
        for tx_hash, tx_mined_status, value, balance in self.wallet.get_history():
            if tx_mined_status.conf:
                timestamp = tx_mined_status.timestamp
                try:
                    time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
                except Exception:
                    time_str = "------"
            else:
                time_str = 'unconfirmed'

            label = self.wallet.get_label(tx_hash)
            if len(label) > 40:
                label = label[0:37] + '...'
            self.history.append( format_str%( time_str, label, format_satoshis(value, whitespaces=True), format_satoshis(balance, whitespaces=True) ) )


    def print_balance(self):
        if not self.network:
            msg = _("Offline")
        elif self.network.is_connected():
            if not self.wallet.up_to_date:
                msg = _("Synchronizing...")
            else:
                c, u, x =  self.wallet.get_balance()
                msg = _("Balance")+": %f  "%(Decimal(c) / COIN)
                if u:
                    msg += "  [%f unconfirmed]"%(Decimal(u) / COIN)
                if x:
                    msg += "  [%f unmatured]"%(Decimal(x) / COIN)
        else:
            msg = _("Not connected")

        self.stdscr.addstr( self.maxy -1, 3, msg)

        for i in range(self.num_tabs):
            self.stdscr.addstr( 0, 2 + 2*i + len(''.join(self.tab_names[0:i])), ' '+self.tab_names[i]+' ', curses.A_BOLD if self.tab == i else 0)

        self.stdscr.addstr(self.maxy -1, self.maxx-30, ' '.join([_("Settings"), _("Network"), _("Quit")]))

    def print_receive(self):
        addr = self.wallet.get_receiving_address()
        self.stdscr.addstr(2, 1, "Address: "+addr)
        self.print_qr(addr)

    def print_contacts(self):
        messages = map(lambda x: "%20s   %45s "%(x[0], x[1][1]), self.contacts.items())
        self.print_list(messages, "%19s  %15s "%("Key", "Value"))

    def print_addresses(self):
        fmt = "%-35s  %-30s"
        messages = map(lambda addr: fmt % (addr, self.wallet.labels.get(addr,"")), self.wallet.get_addresses())
        self.print_list(messages,   fmt % ("Address", "Label"))

    def print_edit_line(self, y, label, text, index, size):
        text += " "*(size - len(text) )
        self.stdscr.addstr( y, 2, label)
        self.stdscr.addstr( y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1))

    def print_send_tab(self):
        self.stdscr.clear()
        self.print_edit_line(3, _("Pay to"), self.str_recipient, 0, 40)
        self.print_edit_line(5, _("Description"), self.str_description, 1, 40)
        self.print_edit_line(7, _("Amount"), self.str_amount, 2, 15)
        self.print_edit_line(9, _("Fee"), self.str_fee, 3, 15)
        self.stdscr.addstr( 12, 15, _("[Send]"), curses.A_REVERSE if self.pos%6==4 else curses.color_pair(2))
        self.stdscr.addstr( 12, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2))
        self.maxpos = 6

    def print_banner(self):
        if self.network and self.network.banner:
            banner = self.network.banner
            banner = banner.replace('\r', '')
            self.print_list(banner.split('\n'))

    def print_qr(self, data):
        import qrcode
        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO

        s = StringIO()
        self.qr = qrcode.QRCode()
        self.qr.add_data(data)
        self.qr.print_ascii(out=s, invert=False)
        msg = s.getvalue()
        lines = msg.split('\n')
        try:
            for i, l in enumerate(lines):
                l = l.encode("utf-8")
                self.stdscr.addstr(i+5, 5, l, curses.color_pair(3))
        except curses.error:
            m = 'error. screen too small?'
            m = m.encode(self.encoding)
            self.stdscr.addstr(5, 1, m, 0)


    def print_list(self, lst, firstline = None):
        lst = list(lst)
        self.maxpos = len(lst)
        if not self.maxpos: return
        if firstline:
            firstline += " "*(self.maxx -2 - len(firstline))
            self.stdscr.addstr( 1, 1, firstline )
        for i in range(self.maxy-4):
            msg = lst[i] if i < len(lst) else ""
            msg += " "*(self.maxx - 2 - len(msg))
            m = msg[0:self.maxx - 2]
            m = m.encode(self.encoding)
            self.stdscr.addstr( i+2, 1, m, curses.A_REVERSE if i == (self.pos % self.maxpos) else 0)

    def refresh(self):
        if self.tab == -1: return
        self.stdscr.border(0)
        self.print_balance()
        self.stdscr.refresh()

    def main_command(self):
        c = self.stdscr.getch()
        print(c)
        cc = curses.unctrl(c).decode()
        if   c == curses.KEY_RIGHT: self.tab = (self.tab + 1)%self.num_tabs
        elif c == curses.KEY_LEFT: self.tab = (self.tab - 1)%self.num_tabs
        elif c == curses.KEY_DOWN: self.pos +=1
        elif c == curses.KEY_UP: self.pos -= 1
        elif c == 9: self.pos +=1 # tab
        elif cc in ['^W', '^C', '^X', '^Q']: self.tab = -1
        elif cc in ['^N']: self.network_dialog()
        elif cc == '^S': self.settings_dialog()
        else: return c
        if self.pos<0: self.pos=0
        if self.pos>=self.maxpos: self.pos=self.maxpos - 1

    def run_tab(self, i, print_func, exec_func):
        while self.tab == i:
            self.stdscr.clear()
            print_func()
            self.refresh()
            c = self.main_command()
            if c: exec_func(c)


    def run_history_tab(self, c):
        if c == 10:
            out = self.run_popup('',["blah","foo"])


    def edit_str(self, target, c, is_num=False):
        # detect backspace
        cc = curses.unctrl(c).decode()
        if c in [8, 127, 263] and target:
            target = target[:-1]
        elif not is_num or cc in '0123456789.':
            target += cc
        return target


    def run_send_tab(self, c):
        if self.pos%6 == 0:
            self.str_recipient = self.edit_str(self.str_recipient, c)
        if self.pos%6 == 1:
            self.str_description = self.edit_str(self.str_description, c)
        if self.pos%6 == 2:
            self.str_amount = self.edit_str(self.str_amount, c, True)
        elif self.pos%6 == 3:
            self.str_fee = self.edit_str(self.str_fee, c, True)
        elif self.pos%6==4:
            if c == 10: self.do_send()
        elif self.pos%6==5:
            if c == 10: self.do_clear()


    def run_receive_tab(self, c):
        if c == 10:
            out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"])

    def run_contacts_tab(self, c):
        if c == 10 and self.contacts:
            out = self.run_popup('Address', ["Copy", "Pay to", "Edit label", "Delete"]).get('button')
            key = list(self.contacts.keys())[self.pos%len(self.contacts.keys())]
            if out == "Pay to":
                self.tab = 1
                self.str_recipient = key
                self.pos = 2
            elif out == "Edit label":
                s = self.get_string(6 + self.pos, 18)
                if s:
                    self.wallet.labels[key] = s

    def run_banner_tab(self, c):
        self.show_message(repr(c))
        pass

    def main(self):

        tty.setraw(sys.stdin)
        try:
            while self.tab != -1:
                self.run_tab(0, self.print_history, self.run_history_tab)
                self.run_tab(1, self.print_send_tab, self.run_send_tab)
                self.run_tab(2, self.print_receive, self.run_receive_tab)
                self.run_tab(3, self.print_addresses, self.run_banner_tab)
                self.run_tab(4, self.print_contacts, self.run_contacts_tab)
                self.run_tab(5, self.print_banner, self.run_banner_tab)
        except curses.error as e:
            raise Exception("Error with curses. Is your screen too small?") from e
        finally:
            tty.setcbreak(sys.stdin)
            curses.nocbreak()
            self.stdscr.keypad(0)
            curses.echo()
            curses.endwin()


    def do_clear(self):
        self.str_amount = ''
        self.str_recipient = ''
        self.str_fee = ''
        self.str_description = ''

    def do_send(self):
        if not is_address(self.str_recipient):
            self.show_message(_('Invalid Litecoin address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * COIN)
        except Exception:
            self.show_message(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * COIN)
        except Exception:
            self.show_message(_('Invalid Fee'))
            return

        if self.wallet.has_password():
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None
        try:
            tx = self.wallet.mktx([TxOutput(TYPE_ADDRESS, self.str_recipient, amount)],
                                  password, self.config, fee)
        except Exception as e:
            self.show_message(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.txid()] = self.str_description

        self.show_message(_("Please wait..."), getchar=False)
        try:
            self.network.run_from_another_thread(self.network.broadcast_transaction(tx))
        except TxBroadcastError as e:
            msg = e.get_message_for_gui()
            self.show_message(msg)
        except BestEffortRequestFailed as e:
            msg = repr(e)
            self.show_message(msg)
        else:
            self.show_message(_('Payment sent.'))
            self.do_clear()
            #self.update_contacts_tab()

    def show_message(self, message, getchar = True):
        w = self.w
        w.clear()
        w.border(0)
        for i, line in enumerate(message.split('\n')):
            w.addstr(2+i,2,line)
        w.refresh()
        if getchar: c = self.stdscr.getch()

    def run_popup(self, title, items):
        return self.run_dialog(title, list(map(lambda x: {'type':'button','label':x}, items)), interval=1, y_pos = self.pos+3)

    def network_dialog(self):
        if not self.network:
            return
        net_params = self.network.get_parameters()
        host, port, protocol = net_params.host, net_params.port, net_params.protocol
        proxy_config, auto_connect = net_params.proxy, net_params.auto_connect
        srv = 'auto-connect' if auto_connect else self.network.default_server
        out = self.run_dialog('Network', [
            {'label':'server', 'type':'str', 'value':srv},
            {'label':'proxy', 'type':'str', 'value':self.config.get('proxy', '')},
            ], buttons = 1)
        if out:
            if out.get('server'):
                server = out.get('server')
                auto_connect = server == 'auto-connect'
                if not auto_connect:
                    try:
                        host, port, protocol = deserialize_server(server)
                    except Exception:
                        self.show_message("Error:" + server + "\nIn doubt, type \"auto-connect\"")
                        return False
            if out.get('server') or out.get('proxy'):
                proxy = electrum.network.deserialize_proxy(out.get('proxy')) if out.get('proxy') else proxy_config
                net_params = NetworkParameters(host, port, protocol, proxy, auto_connect)
                self.network.run_from_another_thread(self.network.set_parameters(net_params))

    def settings_dialog(self):
        fee = str(Decimal(self.config.fee_per_kb()) / COIN)
        out = self.run_dialog('Settings', [
            {'label':'Default fee', 'type':'satoshis', 'value': fee }
            ], buttons = 1)
        if out:
            if out.get('Default fee'):
                fee = int(Decimal(out['Default fee']) * COIN)
                self.config.set_key('fee_per_kb', fee, True)


    def password_dialog(self):
        out = self.run_dialog('Password', [
            {'label':'Password', 'type':'password', 'value':''}
            ], buttons = 1)
        return out.get('Password')


    def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3):
        self.popup_pos = 0

        self.w = curses.newwin( 5 + len(list(items))*interval + (2 if buttons else 0), 50, y_pos, 5)
        w = self.w
        out = {}
        while True:
            w.clear()
            w.border(0)
            w.addstr( 0, 2, title)

            num = len(list(items))

            numpos = num
            if buttons: numpos += 2

            for i in range(num):
                item = items[i]
                label = item.get('label')
                if item.get('type') == 'list':
                    value = item.get('value','')
                elif item.get('type') == 'satoshis':
                    value = item.get('value','')
                elif item.get('type') == 'str':
                    value = item.get('value','')
                elif item.get('type') == 'password':
                    value = '*'*len(item.get('value',''))
                else:
                    value = ''
                if value is None:
                    value = ''
                if len(value)<20:
                    value += ' '*(20-len(value))

                if 'value' in item:
                    w.addstr( 2+interval*i, 2, label)
                    w.addstr( 2+interval*i, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1) )
                else:
                    w.addstr( 2+interval*i, 2, label, curses.A_REVERSE if self.popup_pos%numpos==i else 0)

            if buttons:
                w.addstr( 5+interval*i, 10, "[  ok  ]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-2) else curses.color_pair(2))
                w.addstr( 5+interval*i, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2))

            w.refresh()

            c = self.stdscr.getch()
            if c in [ord('q'), 27]: break
            elif c in [curses.KEY_LEFT, curses.KEY_UP]: self.popup_pos -= 1
            elif c in [curses.KEY_RIGHT, curses.KEY_DOWN]: self.popup_pos +=1
            else:
                i = self.popup_pos%numpos
                if buttons and c==10:
                    if i == numpos-2:
                        return out
                    elif i == numpos -1:
                        return {}

                item = items[i]
                _type = item.get('type')

                if _type == 'str':
                    item['value'] = self.edit_str(item['value'], c)
                    out[item.get('label')] = item.get('value')

                elif _type == 'password':
                    item['value'] = self.edit_str(item['value'], c)
                    out[item.get('label')] = item ['value']

                elif _type == 'satoshis':
                    item['value'] = self.edit_str(item['value'], c, True)
                    out[item.get('label')] = item.get('value')

                elif _type == 'list':
                    choices = item.get('choices')
                    try:
                        j = choices.index(item.get('value'))
                    except Exception:
                        j = 0
                    new_choice = choices[(j + 1)% len(choices)]
                    item['value'] = new_choice
                    out[item.get('label')] = item.get('value')

                elif _type == 'button':
                    out['button'] = item.get('label')
                    break

        return out
示例#18
0
 def confirm_seed(self, seed):
     assert Wallet.is_seed(seed)
     msg = _('Please retype your seed phrase, to confirm that you properly saved it')
     self.restore_seed_dialog(run_prev=self.create_seed, run_next=self.enter_pin, test=lambda x: x==seed, message=msg)
示例#19
0
    def test_update_password_with_app_restarts(self):
        wallet_str = '{"addr_history":{"LMK1a5LKLkLFCEKukwwTrGxPboNvZjDbcY":[],"LPRvUteVjy7MwDYro7o6XJ8SzhaYBJQhoM":[],"LZBc9EVXNXW1aGdrxodATNp9kYeCxufeWb":[]},"addresses":{"change":[],"receiving":["LMK1a5LKLkLFCEKukwwTrGxPboNvZjDbcY","LZBc9EVXNXW1aGdrxodATNp9kYeCxufeWb","LPRvUteVjy7MwDYro7o6XJ8SzhaYBJQhoM"]},"keystore":{"keypairs":{"0344b1588589958b0bcab03435061539e9bcf54677c104904044e4f8901f4ebdf5":"T8hVerMmMsVnq7mkXpEw4krEhXJ5BZNVv7mb4C7LoV8Ni8iywME1","0389508c13999d08ffae0f434a085f4185922d64765c0bff2f66e36ad7f745cc5f":"T96yXyhXKvujT4sMAPihoJJ2sXNTwDircc7WnT2qqXTdBs433uZ5","04575f52b82f159fa649d2a4c353eb7435f30206f0a6cb9674fbd659f45082c37d559ffd19bea9c0d3b7dcc07a7b79f4cffb76026d5d4dff35341efe99056e22d2":"6vHESf1YF8tPdqpGyEiNvibJPRZzKsB4ijYsywkUaz3SfUAnidY"},"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)
        asyncio.run_coroutine_threadsafe(wallet.stop(),
                                         self.asyncio_loop).result()

        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")
示例#20
0
    def test_update_password_of_standard_wallet(self):
        wallet_str = '''{"addr_history":{"LLT9wyJ9BLXsA7riHYi75ZFfxDZxS32oAG":[],"LLwNKFZDfjbB8jkWnzqPF2r3XsBxHu3mHF":[],"LMWQH2yLhZ7VnHx9RF6CpvZPd8ySV5Lanh":[],"LMyDQiayPVgAxmtmfU1B9Mh98GwozAPdCj":[],"LNgcK42YMxmW9FADVuhx4Bm3sWCPTPydxX":[],"LNuiTArKDn23okCnUaHLdUQMfVrvjvjMnU":[],"LPUEAWEFxY956wMN7H8E8ctRpFiM528kSn":[],"LS2GG9wz7M29h2S2Vp9TCVGr1ppHuMvQeL":[],"LSvKsf3Q55rUdtzBmoEjEqDEt2j5NEo9CF":[],"LT16eUG1pRZFXWKDZLCXWrcdvEa9vWyQz8":[],"LTo6Pmy4jeTRr1dsodhym6SvXADh7b69Av":[],"LUCzzEYAvFv65DpGn7BWA4EyBXnQ5evfQJ":[],"LUGUhzEAVatT2jTH9ktAYmF7jMvbPaECbC":[],"LKRixTwrG2FkQYPoRxHxLw6ujam1EHbQAf":[],"LY8mxubJfda3rZL5udixMexVzEXUsqGaNP":[],"LYHvweg8uAa6ACDiTKpC3V6749vk1g26k1":[],"LagAhx4KgpAdpysLSWV8jBS3WPz5YsDTXU":[],"Lajnx2mXFZgtJguqH3C6cS29jck4ago9vq":[],"Lavj6A9GKjrtdVL1KwHeqyCPYAkhyZoFVE":[],"LcJQigi9nbtkUxu6GSjBv2HnETs8jtLNPR":[],"LcjviD3pPN7HiHAn1dYbBwU6NLBwJJrSXZ":[],"LddFDqGsV8XDm9yUf2J37EDNZXtth3N4UF":[],"Le2upsurQXvsBXxP95pt4cJzNKUC6NQTuK":[],"Le4SVbqTuFnyVQe2jkDd2sDpNF79ngHorT":[],"LgE4ERkNimLfKxjMydnoSM23rNqtG5pPYc":[],"Lhz5ZQ1pYxTtuD6V2un762Kd4HByp4QwXB":[]},"addresses":{"change":["Lavj6A9GKjrtdVL1KwHeqyCPYAkhyZoFVE","LagAhx4KgpAdpysLSWV8jBS3WPz5YsDTXU","LPUEAWEFxY956wMN7H8E8ctRpFiM528kSn","LUGUhzEAVatT2jTH9ktAYmF7jMvbPaECbC","LUCzzEYAvFv65DpGn7BWA4EyBXnQ5evfQJ","LcjviD3pPN7HiHAn1dYbBwU6NLBwJJrSXZ"],"receiving":["LNuiTArKDn23okCnUaHLdUQMfVrvjvjMnU","LMWQH2yLhZ7VnHx9RF6CpvZPd8ySV5Lanh","LTo6Pmy4jeTRr1dsodhym6SvXADh7b69Av","LcJQigi9nbtkUxu6GSjBv2HnETs8jtLNPR","Lhz5ZQ1pYxTtuD6V2un762Kd4HByp4QwXB","LMyDQiayPVgAxmtmfU1B9Mh98GwozAPdCj","LddFDqGsV8XDm9yUf2J37EDNZXtth3N4UF","LLT9wyJ9BLXsA7riHYi75ZFfxDZxS32oAG","LLwNKFZDfjbB8jkWnzqPF2r3XsBxHu3mHF","LNgcK42YMxmW9FADVuhx4Bm3sWCPTPydxX","Le4SVbqTuFnyVQe2jkDd2sDpNF79ngHorT","LS2GG9wz7M29h2S2Vp9TCVGr1ppHuMvQeL","LYHvweg8uAa6ACDiTKpC3V6749vk1g26k1","LSvKsf3Q55rUdtzBmoEjEqDEt2j5NEo9CF","Le2upsurQXvsBXxP95pt4cJzNKUC6NQTuK","LT16eUG1pRZFXWKDZLCXWrcdvEa9vWyQz8","LKRixTwrG2FkQYPoRxHxLw6ujam1EHbQAf","LY8mxubJfda3rZL5udixMexVzEXUsqGaNP","Lajnx2mXFZgtJguqH3C6cS29jck4ago9vq","LgE4ERkNimLfKxjMydnoSM23rNqtG5pPYc"]},"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")
示例#21
0
class ElectrumGui:
    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-prux 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)

    def main_command(self):
        self.print_balance()
        c = raw_input("enter command: ")
        if c == "h": self.print_commands()
        elif c == "i": self.print_history()
        elif c == "o": self.enter_order()
        elif c == "p": self.print_order()
        elif c == "s": self.send_order()
        elif c == "r": self.print_addresses()
        elif c == "c": self.print_contacts()
        elif c == "b": self.print_banner()
        elif c == "n": self.network_dialog()
        elif c == "e": self.settings_dialog()
        elif c == "q": self.done = 1
        else: self.print_commands()

    def peers(self):
        print("got peers list:")
        l = filter_protocol(self.wallet.network.get_servers(), 's')
        for s in l:
            print(s)

    def connected(self):
        print("connected")

    def disconnected(self):
        print("disconnected")

    def disconnecting(self):
        print("disconnecting")

    def updated(self):
        s = self.get_balance()
        if s != self.last_balance:
            print(s)
        self.last_balance = s
        return True

    def print_commands(self):
        self.print_list(self.commands, "Available commands")

    def print_history(self):
        width = [20, 40, 14, 14]
        delta = (80 - sum(width) - 4) / 3
        format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%" \
        + "%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s"
        b = 0
        messages = []

        for item in self.wallet.get_history():
            tx_hash, confirmations, value, timestamp, balance = item
            if confirmations:
                try:
                    time_str = datetime.datetime.fromtimestamp(
                        timestamp).isoformat(' ')[:-3]
                except Exception:
                    time_str = "unknown"
            else:
                time_str = 'pending'

            label, is_default_label = self.wallet.get_label(tx_hash)
            messages.append(
                format_str %
                (time_str, label, format_satoshis(value, whitespaces=True),
                 format_satoshis(balance, whitespaces=True)))

        self.print_list(
            messages[::-1], format_str %
            (_("Date"), _("Description"), _("Amount"), _("Balance")))

    def print_balance(self):
        print(self.get_balance())

    def get_balance(self):
        if self.wallet.network.is_connected():
            if not self.wallet.up_to_date:
                msg = _("Synchronizing...")
            else:
                c, u, x = self.wallet.get_balance()
                msg = _("Balance") + ": %f  " % (Decimal(c) / 100000000)
                if u:
                    msg += "  [%f unconfirmed]" % (Decimal(u) / 100000000)
                if x:
                    msg += "  [%f unmatured]" % (Decimal(x) / 100000000)
        else:
            msg = _("Not connected")

        return (msg)

    def print_contacts(self):
        messages = map(lambda x: "%20s   %45s " % (x[0], x[1][1]),
                       self.contacts.items())
        self.print_list(messages, "%19s  %25s " % ("Key", "Value"))

    def print_addresses(self):
        messages = map(
            lambda addr: "%30s    %30s       " %
            (addr, self.wallet.labels.get(addr, "")), self.wallet.addresses())
        self.print_list(messages, "%19s  %25s " % ("Address", "Label"))

    def print_order(self):
        print("send order to " + self.str_recipient + ", amount: " + self.str_amount \
              + "\nfee: " + self.str_fee + ", desc: " + self.str_description)

    def enter_order(self):
        self.str_recipient = raw_input("Pay to: ")
        self.str_description = raw_input("Description : ")
        self.str_amount = raw_input("Amount: ")
        self.str_fee = raw_input("Fee: ")

    def send_order(self):
        self.do_send()

    def print_banner(self):
        for i, x in enumerate(self.wallet.network.banner.split('\n')):
            print(x)

    def print_list(self, list, firstline):
        self.maxpos = len(list)
        if not self.maxpos: return
        print(firstline)
        for i in range(self.maxpos):
            msg = list[i] if i < len(list) else ""
            print(msg)

    def main(self, url):
        while self.done == 0:
            self.main_command()

    def do_send(self):
        if not is_valid(self.str_recipient):
            print(_('Invalid Prux address'))
            return
        try:
            amount = int(Decimal(self.str_amount) * 100000000)
        except Exception:
            print(_('Invalid Amount'))
            return
        try:
            fee = int(Decimal(self.str_fee) * 100000000)
        except Exception:
            print(_('Invalid Fee'))
            return

        if self.wallet.use_encryption:
            password = self.password_dialog()
            if not password:
                return
        else:
            password = None

        c = ""
        while c != "y":
            c = raw_input("ok to send (y/n)?")
            if c == "n": return

        try:
            tx = self.wallet.mktx([(self.str_recipient, amount)], password,
                                  fee)
        except Exception as e:
            print(str(e))
            return

        if self.str_description:
            self.wallet.labels[tx.hash()] = self.str_description

        h = self.wallet.send_tx(tx)
        print(_("Please wait..."))
        self.wallet.tx_event.wait()
        status, msg = self.wallet.receive_tx(h, tx)

        if status:
            print(_('Payment sent.'))
            #self.do_clear()
            #self.update_contacts_tab()
        else:
            print(_('Error'))

    def network_dialog(self):
        print(
            "use 'electrum-prux setconfig server/proxy' to change your network settings"
        )
        return True

    def settings_dialog(self):
        print("use 'electrum-prux setconfig' to change your settings")
        return True

    def password_dialog(self):
        return getpass.getpass()

#   XXX unused

    def run_receive_tab(self, c):
        #if c == 10:
        #    out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"])
        return

    def run_contacts_tab(self, c):
        pass
示例#22
0
config = SimpleConfig({"testnet":
                       True})  # to use ~/.electrum-ltc/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, segwit=True)

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

# you can use ~CLI commands by accessing command_runner
command_runner = Commands(config, wallet=None, 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())
示例#23
0
    def run_and_get_wallet(self, get_wallet_from_daemon):

        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(_('Wallet') + ':'))
        self.name_e = QLineEdit()
        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=_('Electrum-LTC wallet'))

        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 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
示例#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}")