Esempio n. 1
0
    def set_label(self, item, label, changed):
        if self.encode_password is None:
            return
        if not changed:
            return
        try:
            bundle = {
                "label": {
                    "external_id": self.encode(item),
                    "text": self.encode(label)
                }
            }
            params = json.dumps(bundle)
            connection = httplib.HTTPConnection(self.target_host)
            connection.request("POST",
                               ("/api/wallets/%s/labels.json?auth_token=%s" %
                                (self.wallet_id, self.auth_token())), params,
                               {'Content-Type': 'application/json'})

            response = connection.getresponse()
            if response.reason == httplib.responses[httplib.NOT_FOUND]:
                return
            response = json.loads(response.read())
        except socket.gaierror as e:
            print_error('Error connecting to service: %s ' % e)
            return False
Esempio n. 2
0
 def modify_pin():
     try:
         status = self.wallet.get_client().change_pin()
         print_error(status)
         self.handler.show_message(status)
     except Exception, e:
         give_error(e)
Esempio n. 3
0
 def modify_pin():
     try:
         status = self.wallet.get_client().change_pin()
         print_error(status)
         self.handler.show_message(status)
     except Exception, e:
         give_error(e)
Esempio n. 4
0
        def modify_pin():
#            twd.start("Please confirm pin change on Trezor")
            try:
                status = self.wallet.get_client().change_pin()
                print_error(status)
                self.show_message(status)
            except Exception, e:
                give_error(e)
Esempio n. 5
0
 def modify_pin():
     #            twd.start("Please confirm pin change on Trezor")
     try:
         status = self.wallet.get_client().change_pin()
         print_error(status)
         self.show_message(status)
     except Exception, e:
         give_error(e)
Esempio n. 6
0
 def load_theme(self):
     """Load theme retrieved from wallet file."""
     try:
         theme_prefix, theme_path = self.themes[self.theme_name]
     except KeyError:
         util.print_error("Theme not found!", self.theme_name)
         return
     full_theme_path = "%s/%s/style.css" % (theme_prefix, theme_path)
     with open(full_theme_path) as style_file:
         qApp.setStyleSheet(style_file.read())
Esempio n. 7
0
 def load_theme(self):
     """Load theme retrieved from wallet file."""
     try:
         theme_prefix, theme_path = self.themes[self.theme_name]
     except KeyError:
         util.print_error("Theme not found!", self.theme_name)
         return
     full_theme_path = "%s/%s/style.css" % (theme_prefix, theme_path)
     with open(full_theme_path) as style_file:
         qApp.setStyleSheet(style_file.read())
Esempio n. 8
0
    def validate_dnssec(self, url):
        print_error('Checking DNSSEC trust chain for ' + url)
        default = dns.resolver.get_default_resolver()
        ns = default.nameservers[0]
        parts = url.split('.')

        for i in xrange(len(parts), 0, -1):
            sub = '.'.join(parts[i - 1:])
            query = dns.message.make_query(sub, dns.rdatatype.NS)
            response = dns.query.udp(query, ns, 3)
            if response.rcode() != dns.rcode.NOERROR:
                print_error("query error")
                return False

            if len(response.authority) > 0:
                rrset = response.authority[0]
            else:
                rrset = response.answer[0]

            rr = rrset[0]
            if rr.rdtype == dns.rdatatype.SOA:
                #Same server is authoritative, don't check again
                continue

            query = dns.message.make_query(sub,
                                           dns.rdatatype.DNSKEY,
                                           want_dnssec=True)
            response = dns.query.udp(query, ns, 3)
            if response.rcode() != 0:
                print_error("query error")
                return False
                # HANDLE QUERY FAILED (SERVER ERROR OR NO DNSKEY RECORD)

            # answer should contain two RRSET: DNSKEY and RRSIG(DNSKEY)
            answer = response.answer
            if len(answer) != 2:
                print_error("answer error", answer)
                return False

            # the DNSKEY should be self signed, validate it
            name = dns.name.from_text(sub)
            try:
                dns.dnssec.validate(answer[0], answer[1], {name: answer[0]})
            except dns.dnssec.ValidationFailure:
                print_error("validation error")
                return False

        return True
Esempio n. 9
0
    def validate_dnssec(self, url):
        print_error('Checking DNSSEC trust chain for ' + url)
        default = dns.resolver.get_default_resolver()
        ns = default.nameservers[0]
        parts = url.split('.')

        for i in xrange(len(parts), 0, -1):
            sub = '.'.join(parts[i - 1:])
            query = dns.message.make_query(sub, dns.rdatatype.NS)
            response = dns.query.udp(query, ns, 3)
            if response.rcode() != dns.rcode.NOERROR:
                print_error("query error")
                return False

            if len(response.authority) > 0:
                rrset = response.authority[0]
            else:
                rrset = response.answer[0]

            rr = rrset[0]
            if rr.rdtype == dns.rdatatype.SOA:
                #Same server is authoritative, don't check again
                continue

            query = dns.message.make_query(sub,
                                           dns.rdatatype.DNSKEY,
                                           want_dnssec=True)
            response = dns.query.udp(query, ns, 3)
            if response.rcode() != 0:
                print_error("query error")
                return False
                # HANDLE QUERY FAILED (SERVER ERROR OR NO DNSKEY RECORD)

            # answer should contain two RRSET: DNSKEY and RRSIG(DNSKEY)
            answer = response.answer
            if len(answer) != 2:
                print_error("answer error", answer)
                return False

            # the DNSKEY should be self signed, validate it
            name = dns.name.from_text(sub)
            try:
                dns.dnssec.validate(answer[0], answer[1], {name: answer[0]})
            except dns.dnssec.ValidationFailure:
                print_error("validation error")
                return False

        return True
Esempio n. 10
0
 def run(self):
     self.is_running = True
     while self.is_running:
         if not self.keyhash:
             time.sleep(2)
             continue
         if not self.message:
             try:
                 self.message = server.get(self.keyhash)
             except Exception as e:
                 util.print_error("cannot contact cosigner pool")
                 time.sleep(30)
                 continue
             if self.message:
                 self.parent.win.emit(SIGNAL("cosigner:receive"))
         # poll every 30 seconds
         time.sleep(30)
Esempio n. 11
0
 def run(self):
     self.is_running = True
     while self.is_running:
         if not self.keyhash:
             time.sleep(2)
             continue
         if not self.message:
             try:
                 self.message = server.get(self.keyhash)
             except Exception as e:
                 util.print_error("cannot contact cosigner pool")
                 time.sleep(30)
                 continue
             if self.message:
                 self.parent.win.emit(SIGNAL("cosigner:receive"))
         # poll every 30 seconds
         time.sleep(30)
Esempio n. 12
0
    def set_label(self, item,label, changed):
        if self.encode_password is None:
            return
        if not changed:
            return 
        try:
            bundle = {"label": {"external_id": self.encode(item), "text": self.encode(label)}}
            params = json.dumps(bundle)
            connection = httplib.HTTPConnection(self.target_host)
            connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})

            response = connection.getresponse()
            if response.reason == httplib.responses[httplib.NOT_FOUND]:
                return
            response = json.loads(response.read())
        except socket.gaierror as e:
            print_error('Error connecting to service: %s ' %  e)
            return False
Esempio n. 13
0
    def resolve(self, url):
        '''Resolve OpenAlias address using url.'''
        print_error('[OA] Attempting to resolve OpenAlias data for ' + url)

        url = url.replace(
            '@', '.')  # support email-style addresses, per the OA standard
        prefix = chainparams.get_active_chain().code.lower()
        retries = 3
        err = None
        for i in range(0, retries):
            try:
                resolver = dns.resolver.Resolver()
                resolver.timeout = 2.0
                resolver.lifetime = 4.0
                records = resolver.query(url, dns.rdatatype.TXT)
                for record in records:
                    string = record.strings[0]
                    if string.startswith('oa1:' + prefix):
                        address = self.find_regex(
                            string, r'recipient_address=([A-Za-z0-9]+)')
                        name = self.find_regex(string,
                                               r'recipient_name=([^;]+)')
                        if not name:
                            name = address
                        if not address:
                            continue
                        return (address, name)
                QMessageBox.warning(self.win, _('Error'),
                                    _('No OpenAlias record found.'), _('OK'))
                return 0
            except dns.resolver.NXDOMAIN:
                err = _('No such domain.')
                continue
            except dns.resolver.Timeout:
                err = _('Timed out while resolving.')
                continue
            except DNSException:
                err = _('Unhandled exception.')
                continue
            except Exception, e:
                err = _('Unexpected error: ' + str(e))
                continue
            break
Esempio n. 14
0
 def make_seed(self, num_bits=128, prefix=version.SEED_BIP44, custom_entropy=1):
     n = int(math.ceil(math.log(custom_entropy,2)))
     # bits of entropy used by the prefix
     k = len(prefix)*4
     # we add at least 16 bits
     n_added = max(16, k + num_bits - n)
     print_error("make_seed", prefix, "adding %d bits"%n_added)
     my_entropy = ecdsa.util.randrange( pow(2, n_added) )
     nonce = 0
     while True:
         nonce += 1
         i = custom_entropy * (my_entropy + nonce)
         seed = self.mnemonic_encode(i)
         assert i == self.mnemonic_decode(seed)
         if is_old_seed(seed):
             continue
         if is_new_seed(seed, prefix):
             break
     print_error('%d words'%len(seed.split()))
     return seed
Esempio n. 15
0
 def __init__(self, lang=None):
     if lang in [None, '']:
         lang = i18n.language.info().get('language', 'en')
     print_error('language', lang)
     filename = filenames.get(lang[0:2], 'english.txt')
     if getattr( sys, 'frozen' , None):
          path = os.path.join(sys._MEIPASS + "/data/wordlist", filename)
     else:
          path = os.path.join(util.data_dir(), 'wordlist', filename)
     s = open(path,'r').read().strip()
     s = unicodedata.normalize('NFKD', s.decode('utf8'))
     lines = s.split('\n')
     self.wordlist = []
     for line in lines:
         line = line.split('#')[0]
         line = line.strip(' \r')
         assert ' ' not in line
         if line:
             self.wordlist.append(line)
     print_error("wordlist has %d words"%len(self.wordlist))
Esempio n. 16
0
    def do_full_pull(self, force = False):
        connection = httplib.HTTPConnection(self.target_host)
        connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'})
        response = connection.getresponse()
        if response.status != 200:
            print_error("Cannot retrieve labels:", response.status, response.reason)
            return
        response = json.loads(response.read())
        if "error" in response:
            raise BaseException(_("Could not sync labels: %s" % response["error"]))

        for label in response:
            try:
                key = self.decode(label["external_id"])
            except:
                continue
            try:
                value = self.decode(label["text"])
            except:
                continue
            try:
                json.dumps(key)
                json.dumps(value)
            except:
                print_error('error: no json', key)
                continue
            if force or not self.wallet.labels.get(key):
                self.wallet.labels[key] = value
        self.wallet.storage.put('labels', self.wallet.labels)
        print_error("received %d labels"%len(response))
        self.window.labelsChanged.emit()
Esempio n. 17
0
    def resolve(self, url):
        '''Resolve OpenAlias address using url.'''
        print_error('[OA] Attempting to resolve OpenAlias data for ' + url)

        url = url.replace('@', '.')  # support email-style addresses, per the OA standard
        prefix = chainparams.get_active_chain().code.lower()
        retries = 3
        err = None
        for i in range(0, retries):
            try:
                resolver = dns.resolver.Resolver()
                resolver.timeout = 2.0
                resolver.lifetime = 4.0
                records = resolver.query(url, dns.rdatatype.TXT)
                for record in records:
                    string = record.strings[0]
                    if string.startswith('oa1:' + prefix):
                        address = self.find_regex(string, r'recipient_address=([A-Za-z0-9]+)')
                        name = self.find_regex(string, r'recipient_name=([^;]+)')
                        if not name:
                            name = address
                        if not address:
                            continue
                        return (address, name)
                QMessageBox.warning(self.win, _('Error'), _('No OpenAlias record found.'), _('OK'))
                return 0
            except dns.resolver.NXDOMAIN:
                err = _('No such domain.')
                continue
            except dns.resolver.Timeout:
                err = _('Timed out while resolving.')
                continue
            except DNSException:
                err = _('Unhandled exception.')
                continue
            except Exception, e:
                err = _('Unexpected error: ' + str(e))
                continue
            break
Esempio n. 18
0
    def do_full_pull(self, force=False):
        connection = httplib.HTTPConnection(self.target_host)
        connection.request("GET",
                           ("/api/wallets/%s/labels.json?auth_token=%s" %
                            (self.wallet_id, self.auth_token())), "",
                           {'Content-Type': 'application/json'})
        response = connection.getresponse()
        if response.status != 200:
            print_error("Cannot retrieve labels:", response.status,
                        response.reason)
            return
        response = json.loads(response.read())
        if "error" in response:
            raise BaseException(
                _("Could not sync labels: %s" % response["error"]))

        for label in response:
            try:
                key = self.decode(label["external_id"])
            except:
                continue
            try:
                value = self.decode(label["text"])
            except:
                continue
            try:
                json.dumps(key)
                json.dumps(value)
            except:
                print_error('error: no json', key)
                continue
            if force or not self.wallet.labels.get(key):
                self.wallet.labels[key] = value
        self.wallet.storage.put('labels', self.wallet.labels)
        print_error("received %d labels" % len(response))
        self.window.labelsChanged.emit()
Esempio n. 19
0
 def __init__(self, gui, name):
     BasePlugin.__init__(self, gui, name)
     self._is_available = OA_READY
     print_error('OA_READY is ' + str(OA_READY))
     self.previous_payto = ''
Esempio n. 20
0
 def save_favorites(self):
     print_error("Saving new favorite chains: {}".format(
         map(lambda x: x.encode('ascii', 'ignore'), self.favorites)))
     self.parent.config.set_key_above_chain('favorite_chains',
                                            self.favorites, True)
Esempio n. 21
0
    def run(self, action):

        if action == 'new':
            action, wallet_type = self.restore_or_create()
            if wallet_type == 'multisig':
                wallet_type = self.choice(_("Multi Signature Wallet"), 'Select wallet type', [('2of2', _("2 of 2")),('2of3',_("2 of 3")),('mofn',_("M of N"))])
                if not wallet_type:
                    return
            elif wallet_type == 'hardware':
                hardware_wallets = map(lambda x:(x[1],x[2]), filter(lambda x:x[0]=='hardware', chainkey.wallet.wallet_types))
                wallet_type = self.choice(_("Hardware Wallet"), 'Select your hardware wallet', hardware_wallets)
                if not wallet_type:
                    return
            elif wallet_type == 'twofactor':
                wallet_type = '2fa'

            if action == 'create':
                self.storage.put_above_chain('wallet_type', wallet_type, False)

        if action is None:
            return

        if action == 'restore':
            wallet = self.restore(wallet_type)
            if not wallet:
                return
            action = None
        else:
            wallet = Wallet(self.storage)
            action = wallet.get_action()
            # fixme: password is only needed for multiple accounts
            password = None

        # load wallet in plugins
        always_hook('installwizard_load_wallet', wallet, self)

        while action is not None:
            util.print_error("installwizard:", wallet, action)

            if action == 'create_seed':
                seed = wallet.make_seed()
                if not self.show_seed(seed, None):
                    return
                if not self.verify_seed(seed, None):
                    return
                password = self.password_dialog()
                wallet.add_seed(seed, password)
                wallet.create_master_keys(password)

            elif action == 'add_chain':
                if wallet.use_encryption == True:
                    password = self.add_chain_dialog()
                    # workaround pw_decode returning seed if no password is given
                    if password is None:
                        password = '******'
                else:
                    password = None
                try:
                    wallet.create_master_keys(password)
                except Exception:
                    QMessageBox.warning(self, _('Error'), ('Password is incorrect'), _('OK'))
                    return

            elif action == 'add_m_and_n':
                m, n = run_select_mn_dialog()
                if not m or not n:
                    return
                wallet.set_m_and_n(m, n)

            elif action == 'add_cosigner':
                xpub1 = wallet.master_public_keys.get("x1/")
                r = self.multi_mpk_dialog(xpub1, 1)
                if not r:
                    return
                xpub2 = r[0]
                wallet.add_master_public_key("x2/", xpub2)

            elif action == 'add_two_cosigners':
                xpub1 = wallet.master_public_keys.get("x1/")
                r = self.multi_mpk_dialog(xpub1, 2)
                if not r:
                    return
                xpub2, xpub3 = r
                wallet.add_master_public_key("x2/", xpub2)
                wallet.add_master_public_key("x3/", xpub3)

            elif 'add_x_cosigners' in action:
                xpub1 = wallet.master_public_keys.get("x1/")
                cosigners_num = action.split(':')[-1]
                r = self.multi_mpk_dialog(xpub1, int(cosigners_num))
                if not r:
                    return
                for i, xpub in enumerate(r):
                    wallet.add_master_public_key( "x{}/".format(i + 2), xpub )

            elif action == 'create_accounts':
                try:
                    wallet.create_main_account(password)
                except BaseException as e:
                    import traceback
                    traceback.print_exc(file=sys.stdout)
                    QMessageBox.information(None, _('Error'), str(e), _('OK'))
                    return
                self.waiting_dialog(wallet.synchronize)

            else:
                f = always_hook('get_wizard_action', self, wallet, action)
                if not f:
                    raise BaseException('unknown wizard action', action)
                r = f(wallet, self)
                if not r:
                    return

            # next action
            action = wallet.get_action()


        if self.network:
            if self.network.interfaces:
                self.network_dialog()
                # start wallet threads
                wallet.start_threads(self.network)
            else:
                QMessageBox.information(None, _('Warning'), _('You are offline'), _('OK'))


        if action == 'restore':
            self.waiting_dialog(lambda: wallet.restore(self.waiting_label.setText))
            if self.network:
                msg = _("Recovery successful") if wallet.is_found() else _("No transactions found for this seed")
            else:
                msg = _("This wallet was restored offline. It may contain more addresses than displayed.")
            QMessageBox.information(None, _('Information'), msg, _('OK'))

        return wallet
Esempio n. 22
0
 def __init__(self, gui, name):
     BasePlugin.__init__(self, gui, name)
     self._is_available = OA_READY
     print_error('OA_READY is ' + str(OA_READY))
     self.previous_payto = ''
Esempio n. 23
0
 def save_favorites(self):
     print_error("Saving new favorite chains: {}".format(map(lambda x: x.encode('ascii', 'ignore'), self.favorites)))
     self.parent.config.set_key_above_chain('favorite_chains', self.favorites, True)
Esempio n. 24
0
 def close_wallet(self):
     print_error("trezor: clear session")
     if self.wallet and self.wallet.client:
         self.wallet.client.clear_session()
         self.wallet.client.transport.close()
Esempio n. 25
0
 def is_supported_coin(self):
     coins_list = [c.coin_name for c in self.get_client().features.coins]
     print_error('Wallet firmware supported coins: {}'.format(coins_list))
     if self.active_chain.coin_name in coins_list:
         return True
     return False
Esempio n. 26
0
def give_error(message):
    print_error(message)
    raise Exception(message)
Esempio n. 27
0
 def is_supported_coin(self):
     coins_list = [ c.coin_name for c in self.get_client().features.coins ]
     print_error('Wallet firmware supported coins: {}'.format(coins_list))
     if self.active_chain.coin_name in coins_list:
         return True
     return False
Esempio n. 28
0
def give_error(message):
    print_error(message)
    raise Exception(message)
Esempio n. 29
0
 def close_wallet(self):
     print_error("trezor: clear session")
     if self.wallet and self.wallet.client:
         self.wallet.client.clear_session()
         self.wallet.client.transport.close()
Esempio n. 30
0
    def do_full_push(self):
        try:
            bundle = {"labels": {}}
            for key, value in self.wallet.labels.iteritems():
                try:
                    encoded_key = self.encode(key)
                except:
                    print_error('cannot encode', repr(key))
                    continue
                try:
                    encoded_value = self.encode(value)
                except:
                    print_error('cannot encode', repr(value))
                    continue
                bundle["labels"][encoded_key] = encoded_value

            params = json.dumps(bundle)
            connection = httplib.HTTPConnection(self.target_host)
            connection.request(
                "POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" %
                         (self.wallet_id, self.auth_token())), params,
                {'Content-Type': 'application/json'})

            response = connection.getresponse()
            if response.reason == httplib.responses[httplib.NOT_FOUND]:
                print_error('404 error' % e)
                return
            try:
                response = json.loads(response.read())
            except ValueError as e:
                print_error('Error loading labelsync response: %s' % e)
                return False

            if "error" in response:
                print_error('Error loading labelsync response.')
                return False

        except socket.gaierror as e:
            print_error('Error connecting to service: %s ' % e)
            return False

        self.window.labelsChanged.emit()
Esempio n. 31
0
    def do_full_push(self):
        try:
            bundle = {"labels": {}}
            for key, value in self.wallet.labels.iteritems():
                try:
                    encoded_key = self.encode(key)
                except:
                    print_error('cannot encode', repr(key))
                    continue
                try:
                    encoded_value = self.encode(value)
                except:
                    print_error('cannot encode', repr(value))
                    continue
                bundle["labels"][encoded_key] = encoded_value

            params = json.dumps(bundle)
            connection = httplib.HTTPConnection(self.target_host)
            connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})

            response = connection.getresponse()
            if response.reason == httplib.responses[httplib.NOT_FOUND]:
                print_error('404 error' %  e)
                return
            try:
                response = json.loads(response.read())
            except ValueError as e:
                print_error('Error loading labelsync response: %s' %  e)
                return False

            if "error" in response:
                print_error('Error loading labelsync response.')
                return False

        except socket.gaierror as e:
            print_error('Error connecting to service: %s ' %  e)
            return False

        self.window.labelsChanged.emit()