1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-26 16:18:22 +00:00

code style

This commit is contained in:
Jan Pochyla 2017-06-12 18:16:06 +02:00
parent 6e15b37205
commit 98e82e3cd5
18 changed files with 64 additions and 37 deletions

View File

@ -11,9 +11,9 @@ def nth(n):
@unimport @unimport
async def layout_recovery_device(session_id, message): async def layout_recovery_device(session_id, msg):
msg = 'Please enter ' + nth(message.word_count) + ' word' msg = 'Please enter ' + nth(msg.word_count) + ' word'
ui.display.clear() ui.display.clear()
ui.header('Recovery device', ui.ICON_RECOVERY, ui.BLACK, ui.LIGHT_GREEN) ui.header('Recovery device', ui.ICON_RECOVERY, ui.BLACK, ui.LIGHT_GREEN)

View File

@ -42,7 +42,9 @@ __names_obj = [
'Text', 'Text',
] ]
class __dummy: class __dummy:
def __getitem__(self, *args): def __getitem__(self, *args):
return object return object
@ -54,9 +56,11 @@ for __n in __names_get:
for __n in __names_obj: for __n in __names_obj:
globals()[__n] = object globals()[__n] = object
def TypeVar(*args): def TypeVar(*args):
return object return object
def NewType(*args): def NewType(*args):
return lambda x: x return lambda x: x

View File

@ -47,7 +47,7 @@ class TestCase:
else: else:
if places is None: if places is None:
places = 7 places = 7
if round(abs(y-x), places) == 0: if round(abs(y - x), places) == 0:
return return
if not msg: if not msg:
msg = '%r != %r within %r places' % (x, y, places) msg = '%r != %r within %r places' % (x, y, places)
@ -66,7 +66,7 @@ class TestCase:
else: else:
if places is None: if places is None:
places = 7 places = 7
if not (x == y) and round(abs(y-x), places) != 0: if not (x == y) and round(abs(y - x), places) != 0:
return return
if not msg: if not msg:
msg = '%r == %r within %r places' % (x, y, places) msg = '%r == %r within %r places' % (x, y, places)

View File

@ -1,59 +1,69 @@
from TrezorCrypto import AES from TrezorCrypto import AES
def AES_ECB_Encrypt(key: bytes) -> AES: def AES_ECB_Encrypt(key: bytes) -> AES:
''' '''
Create AES encryption context in ECB mode Create AES encryption context in ECB mode
''' '''
return AES(AES.ECB | AES.Encrypt, key) return AES(AES.ECB | AES.Encrypt, key)
def AES_ECB_Decrypt(key: bytes) -> AES: def AES_ECB_Decrypt(key: bytes) -> AES:
''' '''
Create AES decryption context in ECB mode Create AES decryption context in ECB mode
''' '''
return AES(AES.ECB | AES.Decrypt, key) return AES(AES.ECB | AES.Decrypt, key)
def AES_CBC_Encrypt(key: bytes, iv: bytes) -> AES: def AES_CBC_Encrypt(key: bytes, iv: bytes) -> AES:
''' '''
Create AES encryption context in CBC mode Create AES encryption context in CBC mode
''' '''
return AES(AES.CBC | AES.Encrypt, key, iv) return AES(AES.CBC | AES.Encrypt, key, iv)
def AES_CBC_Decrypt(key: bytes, iv: bytes) -> AES: def AES_CBC_Decrypt(key: bytes, iv: bytes) -> AES:
''' '''
Create AES decryption context in CBC mode Create AES decryption context in CBC mode
''' '''
return AES(AES.CBC | AES.Decrypt, key, iv) return AES(AES.CBC | AES.Decrypt, key, iv)
def AES_CFB_Encrypt(key: bytes, iv: bytes) -> AES: def AES_CFB_Encrypt(key: bytes, iv: bytes) -> AES:
''' '''
Create AES encryption context in CFB mode Create AES encryption context in CFB mode
''' '''
return AES(AES.CFB | AES.Encrypt, key, iv) return AES(AES.CFB | AES.Encrypt, key, iv)
def AES_CFB_Decrypt(key: bytes, iv: bytes) -> AES: def AES_CFB_Decrypt(key: bytes, iv: bytes) -> AES:
''' '''
Create AES decryption context in CFB mode Create AES decryption context in CFB mode
''' '''
return AES(AES.CFB | AES.Decrypt, key, iv) return AES(AES.CFB | AES.Decrypt, key, iv)
def AES_OFB_Encrypt(key: bytes, iv: bytes) -> AES: def AES_OFB_Encrypt(key: bytes, iv: bytes) -> AES:
''' '''
Create AES encryption context in OFB mode Create AES encryption context in OFB mode
''' '''
return AES(AES.OFB | AES.Encrypt, key, iv) return AES(AES.OFB | AES.Encrypt, key, iv)
def AES_OFB_Decrypt(key: bytes, iv: bytes) -> AES: def AES_OFB_Decrypt(key: bytes, iv: bytes) -> AES:
''' '''
Create AES decryption context in OFB mode Create AES decryption context in OFB mode
''' '''
return AES(AES.OFB | AES.Decrypt, key, iv) return AES(AES.OFB | AES.Decrypt, key, iv)
def AES_CTR_Encrypt(key: bytes) -> AES: def AES_CTR_Encrypt(key: bytes) -> AES:
''' '''
Create AES encryption context in CTR mode Create AES encryption context in CTR mode
''' '''
return AES(AES.CTR | AES.Encrypt, key) return AES(AES.CTR | AES.Encrypt, key)
def AES_CTR_Decrypt(key: bytes) -> AES: def AES_CTR_Decrypt(key: bytes) -> AES:
''' '''
Create AES decryption context in CTR mode Create AES decryption context in CTR mode

View File

@ -16,6 +16,7 @@
# 58 character alphabet used # 58 character alphabet used
_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' _alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def encode(data: bytes) -> str: def encode(data: bytes) -> str:
''' '''
Convert bytes to base58 encoded string. Convert bytes to base58 encoded string.
@ -55,7 +56,7 @@ def decode(string: str) -> bytes:
acc, mod = divmod(acc, 256) acc, mod = divmod(acc, 256)
result.append(mod) result.append(mod)
return bytes((b for b in reversed(result +[0] * (origlen - newlen)))) return bytes((b for b in reversed(result + [0] * (origlen - newlen))))
def encode_check(data: bytes, digestfunc=None) -> str: def encode_check(data: bytes, digestfunc=None) -> str:
@ -67,6 +68,7 @@ def encode_check(data: bytes, digestfunc=None) -> str:
digestfunc = lambda x: sha256(sha256(x).digest()).digest()[:4] digestfunc = lambda x: sha256(sha256(x).digest()).digest()[:4]
return encode(data + digestfunc(data)) return encode(data + digestfunc(data))
def decode_check(string: str, digestfunc=None) -> bytes: def decode_check(string: str, digestfunc=None) -> bytes:
''' '''
Convert base58 encoded string to bytes and verify checksum. Convert base58 encoded string to bytes and verify checksum.

View File

@ -1,5 +1,6 @@
class Hmac: class Hmac:
def __init__(self, key, msg, digestmod): def __init__(self, key, msg, digestmod):
self.__digestmod = digestmod self.__digestmod = digestmod
self.__inner = digestmod() self.__inner = digestmod()

View File

@ -20,29 +20,37 @@ _leveldict = {
level = NOTSET level = NOTSET
color = True color = True
def _log(name, mlevel, msg, *args): def _log(name, mlevel, msg, *args):
if __debug__ and mlevel >= level: if __debug__ and mlevel >= level:
if color: if color:
fmt = '%d \x1b[35m%s\x1b[0m %s \x1b[' + _leveldict[mlevel][1] + 'm' + msg + '\x1b[0m' fmt = '%d \x1b[35m%s\x1b[0m %s \x1b[' + \
_leveldict[mlevel][1] + 'm' + msg + '\x1b[0m'
else: else:
fmt = '%d %s %s ' + msg fmt = '%d %s %s ' + msg
print(fmt % ((utime.ticks_us(), name, _leveldict[mlevel][0]) + args)) print(fmt % ((utime.ticks_us(), name, _leveldict[mlevel][0]) + args))
def debug(name, msg, *args): def debug(name, msg, *args):
_log(name, DEBUG, msg, *args) _log(name, DEBUG, msg, *args)
def info(name, msg, *args): def info(name, msg, *args):
_log(name, INFO, msg, *args) _log(name, INFO, msg, *args)
def warning(name, msg, *args): def warning(name, msg, *args):
_log(name, WARNING, msg, *args) _log(name, WARNING, msg, *args)
def error(name, msg, *args): def error(name, msg, *args):
_log(name, ERROR, msg, *args) _log(name, ERROR, msg, *args)
def exception(name, exc): def exception(name, exc):
_log(name, ERROR, 'exception:') _log(name, ERROR, 'exception:')
sys.print_exception(exc) sys.print_exception(exc)
def critical(name, msg, *args): def critical(name, msg, *args):
_log(name, CRITICAL, msg, *args) _log(name, CRITICAL, msg, *args)

View File

@ -287,6 +287,7 @@ class Wait(Syscall):
self.exit() self.exit()
raise raise
select = Select select = Select
sleep = Sleep sleep = Sleep
wait = Wait wait = Wait

View File

@ -3,6 +3,7 @@ try:
except ImportError: except ImportError:
resdata = None resdata = None
def load(name): def load(name):
''' '''
Loads resource of a given name as bytes. Loads resource of a given name as bytes.
@ -12,6 +13,7 @@ def load(name):
with open(name, 'rb') as f: with open(name, 'rb') as f:
return f.read() return f.read()
def gettext(message): def gettext(message):
''' '''
Returns localized string. This function is aliased to _. Returns localized string. This function is aliased to _.

View File

@ -116,8 +116,14 @@ class Button(Widget):
ax, ay, aw, ah = self.area ax, ay, aw, ah = self.area
tx = ax + aw // 2 tx = ax + aw // 2
ty = ay + ah // 2 + 8 ty = ay + ah // 2 + 8
display.bar_radius(ax, ay, aw, ah, style['border-color'], ui.BLACK, style['radius']) display.bar_radius(ax, ay, aw, ah,
display.bar_radius(ax + 1, ay + 1, aw - 2, ah - 2, style['bg-color'], style['border-color'], style['radius']) style['border-color'],
ui.BLACK,
style['radius'])
display.bar_radius(ax + 1, ay + 1, aw - 2, ah - 2,
style['bg-color'],
style['border-color'],
style['radius'])
if isinstance(self.content, str): if isinstance(self.content, str):
display.text_center(tx, ty, self.content, display.text_center(tx, ty, self.content,

View File

@ -11,6 +11,7 @@ CANCELLED = const(2)
class ConfirmDialog(Widget): class ConfirmDialog(Widget):
def __init__(self, content=None, confirm='Confirm', cancel='Cancel'): def __init__(self, content=None, confirm='Confirm', cancel='Cancel'):
self.content = content self.content = content
if cancel is not None: if cancel is not None:
@ -44,6 +45,7 @@ class ConfirmDialog(Widget):
class HoldToConfirmDialog(Widget): class HoldToConfirmDialog(Widget):
def __init__(self, content=None, hold='Hold to confirm', *args, **kwargs): def __init__(self, content=None, hold='Hold to confirm', *args, **kwargs):
self.button = Button((0, 240 - 48, 240, 48), hold, self.button = Button((0, 240 - 48, 240, 48), hold,
normal_style=CONFIRM_BUTTON, normal_style=CONFIRM_BUTTON,

View File

@ -10,8 +10,8 @@ class Container(Widget):
for child in self.children: for child in self.children:
child.render() child.render()
def send(self, event, pos): def touch(self, event, pos):
for child in self.children: for child in self.children:
result = child.send(event, pos) result = child.touch(event, pos)
if result is not None: if result is not None:
return result return result

View File

@ -43,7 +43,7 @@ def compute_mask(text):
return mask return mask
class KeyboardMultiTap: class KeyboardMultiTap(ui.Widget):
def __init__(self, content=''): def __init__(self, content=''):
self.content = content self.content = content
@ -162,7 +162,7 @@ def zoom_buttons(keys, upper=False):
return [Button(cell_area(i, n_x, n_y), key) for i, key in enumerate(keys)] return [Button(cell_area(i, n_x, n_y), key) for i, key in enumerate(keys)]
class KeyboardZooming: class KeyboardZooming(ui.Widget):
def __init__(self, content='', uppercase=True): def __init__(self, content='', uppercase=True):
self.content = content self.content = content

View File

@ -19,7 +19,7 @@ DEFAULT_LOADER_ACTIVE = {
_LOADER_MSEC = const(1000) _LOADER_MSEC = const(1000)
class Loader: class Loader(ui.Widget):
def __init__(self, normal_style=None, active_style=None): def __init__(self, normal_style=None, active_style=None):
self.start_ticks_ms = None self.start_ticks_ms = None

View File

@ -21,7 +21,7 @@ def generate_digits():
return digits return digits
class PinMatrix(): class PinMatrix(ui.Widget):
def __init__(self, label, pin=''): def __init__(self, label, pin=''):
self.label = label self.label = label
@ -67,10 +67,10 @@ class PinMatrix():
# display.bar(0, 95, 240, 2, ui.blend(ui.BLACK, ui.WHITE, 0.25)) # display.bar(0, 95, 240, 2, ui.blend(ui.BLACK, ui.WHITE, 0.25))
# display.bar(0, 142, 240, 2, ui.blend(ui.BLACK, ui.WHITE, 0.25)) # display.bar(0, 142, 240, 2, ui.blend(ui.BLACK, ui.WHITE, 0.25))
def send(self, event, pos): def touch(self, event, pos):
if self.clear_button.send(event, pos) == BTN_CLICKED: if self.clear_button.touch(event, pos) == BTN_CLICKED:
self.pin = '' self.pin = ''
for btn in self.pin_buttons: for btn in self.pin_buttons:
if btn.send(event, pos) == BTN_CLICKED: if btn.touch(event, pos) == BTN_CLICKED:
if len(self.pin) < 9: if len(self.pin) < 9:
self.pin += btn.content self.pin += btn.content

View File

@ -1,7 +1,7 @@
from trezor import ui from trezor import ui
class Qr: class Qr(ui.Widget):
def __init__(self, data, pos, scale): def __init__(self, data, pos, scale):
self.data = data self.data = data
@ -10,6 +10,3 @@ class Qr:
def render(self): def render(self):
ui.display.qrcode(self.pos[0], self.pos[1], self.data, self.scale) ui.display.qrcode(self.pos[0], self.pos[1], self.data, self.scale)
def send(self, event, pos):
pass

View File

@ -13,7 +13,8 @@ SWIPE_LEFT = const(90)
SWIPE_RIGHT = const(270) SWIPE_RIGHT = const(270)
class Swipe(): class Swipe(ui.Widget):
def __init__(self, area=None, absolute=False): def __init__(self, area=None, absolute=False):
self.area = area or (0, 0, ui.SCREEN, ui.SCREEN) self.area = area or (0, 0, ui.SCREEN, ui.SCREEN)
self.absolute = absolute self.absolute = absolute
@ -22,7 +23,7 @@ class Swipe():
self.light_origin = None self.light_origin = None
self.light_target = ui.BACKLIGHT_NONE self.light_target = ui.BACKLIGHT_NONE
def send(self, event, pos): def touch(self, event, pos):
if not self.absolute: if not self.absolute:
pos = rotate_coords(pos) pos = rotate_coords(pos)
@ -42,8 +43,8 @@ class Swipe():
velya = abs(pdy / td) if td > 0 else 1 velya = abs(pdy / td) if td > 0 else 1
ratio = int(pdxa / pdya * 100) if pdya > 0 else 100 ratio = int(pdxa / pdya * 100) if pdya > 0 else 100
if (velya >= _SWIPE_VELOCITY_THRESHOLD if (velya >= _SWIPE_VELOCITY_THRESHOLD
and pdya >= _SWIPE_DISTANCE_THRESHOLD and pdya >= _SWIPE_DISTANCE_THRESHOLD
and ratio <= _SWIPE_RATIO_THRESHOLD): and ratio <= _SWIPE_RATIO_THRESHOLD):
light = ui.display.backlight() light = ui.display.backlight()
if light > self.light_target: if light > self.light_target:
light -= 5 light -= 5
@ -68,16 +69,16 @@ class Swipe():
velxa = abs(pdx / td) velxa = abs(pdx / td)
ratio = int(pdya / pdxa * 100) if pdxa > 0 else 100 ratio = int(pdya / pdxa * 100) if pdxa > 0 else 100
if (velxa >= _SWIPE_VELOCITY_THRESHOLD if (velxa >= _SWIPE_VELOCITY_THRESHOLD
and pdxa >= _SWIPE_DISTANCE_THRESHOLD and pdxa >= _SWIPE_DISTANCE_THRESHOLD
and ratio <= _SWIPE_RATIO_THRESHOLD): and ratio <= _SWIPE_RATIO_THRESHOLD):
return SWIPE_RIGHT if pdx > 0 else SWIPE_LEFT return SWIPE_RIGHT if pdx > 0 else SWIPE_LEFT
else: else:
# Vertical direction # Vertical direction
velya = abs(pdy / td) velya = abs(pdy / td)
ratio = int(pdxa / pdya * 100) if pdya > 0 else 100 ratio = int(pdxa / pdya * 100) if pdya > 0 else 100
if (velya >= _SWIPE_VELOCITY_THRESHOLD if (velya >= _SWIPE_VELOCITY_THRESHOLD
and pdya >= _SWIPE_DISTANCE_THRESHOLD and pdya >= _SWIPE_DISTANCE_THRESHOLD
and ratio <= _SWIPE_RATIO_THRESHOLD): and ratio <= _SWIPE_RATIO_THRESHOLD):
if pdy < 0: if pdy < 0:
ui.display.backlight(self.light_origin) ui.display.backlight(self.light_origin)
return SWIPE_DOWN if pdy > 0 else SWIPE_UP return SWIPE_DOWN if pdy > 0 else SWIPE_UP
@ -85,10 +86,3 @@ class Swipe():
self.start_pos = None self.start_pos = None
self.start_time = 0 self.start_time = 0
ui.display.backlight(self.light_origin) ui.display.backlight(self.light_origin)
def __iter__(self):
while True:
event, *pos = yield loop.Select(loop.TOUCH)
result = self.send(event, pos)
if result is not None:
return result

View File

@ -111,4 +111,4 @@ def encode_session_open(session_id, callback):
def encode_session_close(session_id, callback): def encode_session_close(session_id, callback):
# v1 codec does not have explicit session support # v1 codec does not have explicit session support
pass pass