def commit(self): # data to save # - important that this fails immediately when nvram overflows from common import settings obj = self.serialize() v = settings.get('multisig', []) orig = v.copy() if not v or self.storage_idx == -1: # create self.storage_idx = len(v) v.append(obj) else: # update: no provision for changing fingerprints assert sorted(k for k, v in v[self.storage_idx][2]) == self.xfps v[self.storage_idx] = obj settings.set('multisig', v) # save now, rather than in background, so we can recover # from out-of-space situation try: settings.save() except: # back out change; no longer sure of NVRAM state try: settings.set('multisig', orig) settings.save() except: pass # give up on recovery raise MultisigOutOfSpace
async def choose_first_address(*a): # Choose from a truncated list of index 0 common addresses, remember # the last address the user selected and use it as the default from common import settings, dis chain = chains.current_chain() dis.fullscreen('Loading...') with stash.SensitiveValues() as sv: def truncate_address(addr): # Truncates address to width of screen, replacing middle chars middle = "-" leftover = SCREEN_CHAR_WIDTH - len(middle) start = addr[0:(leftover + 1) // 2] end = addr[len(addr) - (leftover // 2):] return start + middle + end # Create list of choices (address_index_0, path, addr_fmt) choices = [] for name, path, addr_fmt in chains.CommonDerivations: if '{coin_type}' in path: path = path.replace('{coin_type}', str(chain.b44_cointype)) subpath = path.format(account=0, change=0, idx=0) node = sv.derive_path(subpath, register=False) address = chain.address(node, addr_fmt) choices.append((truncate_address(address), path, addr_fmt)) dis.progress_bar_show(len(choices) / len(chains.CommonDerivations)) stash.blank_object(node) picked = None async def clicked(_1, _2, item): if picked is None: picked = item.arg the_ux.pop() items = [ MenuItem(address, f=clicked, arg=i) for i, (address, path, addr_fmt) in enumerate(choices) ] menu = MenuSystem(items, title='Address List') menu.goto_idx(settings.get('axi', 0)) the_ux.push(menu) await menu.interact() if picked is None: return None # update last clicked address settings.set('axi', picked) address, path, addr_fmt = choices[picked] return (path, addr_fmt)
def set_colorspace(self, colorspace): if colorspace == 'LUV': self.luv_radio.set_active(True) else: self.hsv_radio.set_active(True) settings.set('camera/colorspace', colorspace) self.preprocessor.set_colorspace(colorspace) self.processor.refresh()
def _static_processing(self): logger.info("Static processing thread starting") idx = -1 # resume processing with the last image the user looked at last_img = settings.get('processing/last_img', None) for i, image_name in enumerate(self.images): if image_name == last_img: self.idx = i break while True: with self.condition: # wait until the user hits a key while idx == self.idx and not self.do_stop and not self.do_refresh: self.condition.wait() if self.do_stop: break idx = self.idx self.do_refresh = False # if the index is valid, then process an image if idx < len(self.images) and idx >= 0: image_name = self.images[idx] logger.info("Opening %s" % image_name) img = cv2.imread(image_name) if img is None: logger.error("Error opening %s: could not read file" % (image_name)) self.idx += self.idx_increment continue try: target_data = self.detector.processImage(img) except: logutil.log_exception(logger, 'error processing image') else: settings.set('processing/last_img', image_name) settings.save() logger.info('Finished processing') # note that you cannot typically interact with the UI # from another thread -- but this function is special self.camera_widget.set_target_data(target_data) logger.info("Static processing thread exiting")
def delete(self): # remove saved entry # - important: not expecting more than one instance of this class in memory from common import settings assert self.storage_idx >= 0 # safety check expect_idx = self.find_match(self.M, self.N, self.xfps) assert expect_idx == self.storage_idx lst = settings.get('multisig', []) del lst[self.storage_idx] settings.set('multisig', lst) settings.save() self.storage_idx = -1
def initialize(self): # store references to these so we don't have to do it later self.thresh_widgets = [getattr(self, 'adj_%s' % name) for name in self.thresh_names] # always setup builtins, they shouldn't change at all default_settings = None for name, setting, is_default in self.settings: if is_default: default_settings = setting settings.set('camera/thresholds/%s' % name, setting) # setup widgets with thresholds # -> this implicitly sets up the detector correctly, since the widget # change event changes the detector value current_thresholds = [settings.get('camera/%s' % name, default) for name, default in izip(self.thresh_names, default_settings)] current_thresholds.append(settings.get('camera/colorspace', 'HSV')) self.set_thresholds(current_thresholds) # initialize the combo box with existing settings # -> but block the handler, so we don't accidentally set the settings again self.thresh_selection_combo.handler_block_by_func(self.on_thresh_selection_combo_changed) for i, (name, value) in enumerate(settings.items('camera/thresholds')): self.thresh_model.append((name,)) # if the value matches completely, set this as the currently selected setting # -> this way, the user knows the current settings aren't saved! match = True for tvalue, cvalue in izip(value, current_thresholds[:6]): if int(tvalue) != int(cvalue): match = False break if match: self.thresh_selection_combo.set_active(i) self.thresh_selection_combo.handler_unblock_by_func(self.on_thresh_selection_combo_changed)
def initialize(self): # store references to these so we don't have to do it later self.thresh_widgets = [getattr(self, 'adj_%s' % name) for name in self.thresh_names] # always setup builtins, they shouldn't change at all settings.set('camera/thresholds/Competition', self.kCompSettings) settings.set('camera/thresholds/Pit', self.kPitSettings) # setup widgets with thresholds # -> this implicitly sets up the detector correctly, since the widget # change event changes the detector value current_thresholds = [settings.get('camera/%s' % name, default) for name, default in izip(self.thresh_names, self.kCompSettings)] self.set_thresholds(current_thresholds) # initialize the combo box with existing settings # -> but block the handler, so we don't accidentally set the settings again self.thresh_selection_combo.handler_block_by_func(self.on_thresh_selection_combo_changed) for i, (name, value) in enumerate(settings.items('camera/thresholds')): self.thresh_model.append((name,)) # if the value matches completely, set this as the currently selected setting # -> this way, the user knows the current settings aren't saved! match = True for tvalue, cvalue in izip(value, current_thresholds): if int(tvalue) != int(cvalue): match = False break if match: self.thresh_selection_combo.set_active(i) self.thresh_selection_combo.handler_unblock_by_func(self.on_thresh_selection_combo_changed) # initialize aim height variable aim_horizontal = settings.get('targeting/aim_horizontal', target_data.kOptimumHorizontalPosition) self.adj_aim_horizontal.set_value(aim_horizontal * 100.0) aim_vertical = settings.get('targeting/aim_vertical', target_data.kOptimumVerticalPosition) self.adj_aim_vertical.set_value(aim_vertical * 100.0)
def capture_xpub(self): # track my xpubkey fingerprint & value in settings (not sensitive really) # - we share these on any USB connection from common import settings # Implicit in the values is the BIP39 encryption passphrase, # which we might not want to actually store. # TODO: trezorcrypto doesn't implement this, but implement fingerprint() instead, which apparently # returns the fingerprint of the parent?!?!?!? xfp = self.node.my_fingerprint() xpub = self.chain.serialize_public(self.node) if self._bip39pw: settings.set_volatile('xfp', xfp) settings.set_volatile('xpub', xpub) else: settings.overrides.clear() settings.set('xfp', xfp) settings.set('xpub', xpub) settings.set('chain', self.chain.ctype) settings.set('words', (self.mode == 'words'))
def on_autonomous_choices_updated(self, choices): settings.set('autonomous/choices', choices)
def save_thresholds(self, name, thresholds): settings.set('camera/thresholds/%s' % name, thresholds)
async def restore_from_dict(vals): # Restore from a dict of values. Already JSON decoded. # Reboot on success, return string on failure from common import pa, dis, settings from pincodes import SE_SECRET_LEN #print("Restoring from: %r" % vals) # step1: the private key # - prefer raw_secret over other values # - TODO: fail back to other values try: chain = chains.get_chain(vals.get('chain', 'BTC')) assert 'raw_secret' in vals raw = bytearray(SE_SECRET_LEN) rs = vals.pop('raw_secret') if len(rs) % 2: rs += '0' x = a2b_hex(rs) raw[0:len(x)] = x # check we can decode this right (might be different firmare) opmode, bits, node = stash.SecretStash.decode(raw) assert node # verify against xprv value (if we have it) if 'xprv' in vals: check_xprv = chain.serialize_private(node) assert check_xprv == vals['xprv'], 'xprv mismatch' except Exception as e: return ('Unable to decode raw_secret and ' 'restore the seed value!\n\n\n' + str(e)) ls = None if 'long_secret' in vals: try: ls = a2b_hex(vals.pop('long_secret')) except Exception as exc: sys.print_exception(exc) # but keep going. dis.fullscreen("Saving...") dis.progress_bar_show(.25) # clear (in-memory) settings and change also nvram key # - also captures xfp, xpub at this point pa.change(new_secret=raw) # force the right chain pa.new_main_secret(raw, chain) # updates xfp/xpub # NOTE: don't fail after this point... they can muddle thru w/ just right seed if ls is not None: try: pa.ls_change(ls) except Exception as exc: sys.print_exception(exc) # but keep going # restore settings from backup file for idx, k in enumerate(vals): dis.progress_bar_show(idx / len(vals)) if not k.startswith('setting.'): continue if k == 'xfp' or k == 'xpub': continue settings.set(k[8:], vals[k]) # write out settings.save() if ('hsm_policy' in vals): import hsm hsm.restore_backup(vals['hsm_policy']) await ux_show_story( 'Everything has been successfully restored. ' 'We must now reboot to install the ' 'updated settings and/or seed.', title='Success!') from machine import reset reset()
def _on_thresh(self, widget, name): v = widget.get_value() settings.set('camera/%s' % name, v) setattr(self.preprocessor, name, v) self.processor.refresh()
def xset(idx, text): from common import settings settings.set('pms', idx)
def on_adj_aim_vertical_value_changed(self, widget): value = widget.get_value() * 0.01 self.processor.detector.kOptimumVerticalPosition = value self.targeter.kOptimumVerticalPosition = value settings.set('targeting/aim_vertical', value) self.processor.refresh()