Skip to content

Commit

Permalink
Satochip: clean code using flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
Toporin committed Mar 20, 2024
1 parent 7a8d6ca commit 7193d88
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 42 deletions.
16 changes: 8 additions & 8 deletions electrum/plugins/satochip/qt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from electrum.simple_config import SimpleConfig
from electrum.gui.qt.util import (EnterButton, Buttons, CloseButton, OkButton, CancelButton, WindowModalDialog, WWLabel, PasswordLineEdit)
from electrum.gui.qt.qrcodewidget import QRCodeWidget, QRDialog
from electrum.gui.qt.wizard.wallet import WCScriptAndDerivation, WCHWUnlock, WCHWUninitialized, WCHWXPub, WalletWizardComponent
from electrum.gui.qt.wizard.wallet import WCScriptAndDerivation, WCHWUnlock, WCHWUninitialized, WCHWXPub, WalletWizardComponent, QENewWalletWizard
from electrum.plugin import hook
from PyQt5.QtCore import Qt, pyqtSignal, QRegExp
from PyQt5.QtGui import QRegExpValidator
Expand Down Expand Up @@ -728,7 +728,7 @@ class SatochipSetupLayout(QVBoxLayout):
def __init__(self, device):
_logger.info("[SatochipSetupLayout] __init__()")
QVBoxLayout.__init__(self)

vbox = QVBoxLayout()

# intro
Expand All @@ -753,7 +753,7 @@ def __init__(self, device):
self.addLayout(vbox2)

# PIN validation
if (self.pw.text()=="" or self.pw.text()==None):
if (self.pw.text()=="" or self.pw.text() is None):
self.validChanged.emit(False)

def set_enabled():
Expand Down Expand Up @@ -801,7 +801,7 @@ def on_ready(self):
def on_settings_valid_changed(self, is_valid: bool):
_logger.info(f"[WCSatochipSetupParams] on_settings_valid_changed() is_valid: {is_valid}")
self.valid = is_valid

def apply(self):
_logger.info("[WCSatochipSetupParams] apply()")
current_cosigner = self.wizard.current_cosigner(self.wizard_data)
Expand All @@ -812,7 +812,7 @@ class WCSatochipSetup(WalletWizardComponent):
def __init__(self, parent, wizard):
WalletWizardComponent.__init__(self, parent, wizard, title=_('Satochip Setup'))
_logger.info('[WCSatochipSetup] __init__()') # debugsatochip

self.plugins = wizard.plugins
self.plugin = self.plugins.get_plugin('satochip')

Expand Down Expand Up @@ -865,7 +865,7 @@ class SatochipSeedLayout(QVBoxLayout):

def __init__(self, device):
QVBoxLayout.__init__(self)

label = QLabel(_("Enter a label to name your device:"))
self.label_e = QLineEdit()
hl = QHBoxLayout()
Expand All @@ -877,7 +877,7 @@ def __init__(self, device):
self.text_e = QTextEdit()
self.text_e.setMaximumHeight(60)
msg = _("Enter your BIP39 mnemonic:")

# TODO: validation?
def set_enabled():
item = ' '.join(str(clean_text(self.text_e)).split())
Expand Down Expand Up @@ -973,4 +973,4 @@ def initialize_device_task(settings, device_id, handler):
t.start()

def apply(self):
pass
pass
54 changes: 20 additions & 34 deletions electrum/plugins/satochip/satochip.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
from electrum import descriptor
from electrum.bitcoin import TYPE_ADDRESS, int_to_hex, var_int
from electrum.i18n import _
from electrum.plugin import Device, runs_in_hwd_thread
from electrum.keystore import Hardware_KeyStore, bip39_to_seed, bip39_is_checksum_valid
from electrum.plugin import Device, DeviceInfo
from electrum.keystore import Hardware_KeyStore, bip39_to_seed, bip39_is_checksum_valid, ScriptTypeNotSupported
from electrum.transaction import Transaction
from electrum.wallet import Standard_Wallet
from electrum.wizard import NewWalletWizard
from electrum.util import bfh, versiontuple, UserFacingException
from electrum.crypto import hash_160, sha256d
from electrum.ecc import CURVE_ORDER, der_sig_from_r_and_s, get_r_and_s_from_der_sig, ECPubkey
Expand Down Expand Up @@ -64,17 +65,6 @@ def __init__(self, plugin: HW_PluginBase, handler):
self.handler = handler
#self.parser= CardDataParser()
self.cc= CardConnector(self, _logger.getEffectiveLevel())
self.ux_busy= False

def show_error(self, message, clear_client=False):
_logger.error(f"[SatochipClient] show_error() {message}")
if not self.ux_busy:
self.handler.show_error(message)
else:
self.ux_busy = False
if clear_client:
self.client = None
#raise UserFacingException(message)

def __repr__(self):
return '<SatochipClient TODO>'
Expand Down Expand Up @@ -132,28 +122,27 @@ def has_usable_connection_with_device(self):
def verify_PIN(self, pin=None):
while(True):
try:
print("DEBUG verify pin")
#when pin is None, pysatochip use a cached pin if available
(response, sw1, sw2)= self.cc.card_verify_PIN_simple(pin)
return True

# recoverable errors
except CardNotPresentError:
msg = f"No card found! \nPlease insert card, then enter your PIN:"
(is_PIN, pin)= self.PIN_dialog(msg)
if is_PIN == False:
(is_PIN, pin)= self.PIN_dialog(msg)
if is_PIN is False:
return False
except PinRequiredError as ex:
# no pin value cached in pysatochip
msg = f'Enter the PIN for your card:'
(is_PIN, pin)= self.PIN_dialog(msg)
if is_PIN == False:
(is_PIN, pin)= self.PIN_dialog(msg)
if is_PIN is False:
return False
except WrongPinError as ex:
pin= None # reset pin
msg = f"Wrong PIN! {ex.pin_left} tries remaining! \n Enter the PIN for your card:"
(is_PIN, pin)= self.PIN_dialog(msg)
if is_PIN == False:
(is_PIN, pin)= self.PIN_dialog(msg)
if is_PIN is False:
return False

# unrecoverable errors
Expand Down Expand Up @@ -194,7 +183,7 @@ def get_xpub(self, bip32_path, xtype):
def ping_check(self):
#check connection is working
try:
print('ping_check')#debug
_logger.info('[SatochipClient] ping_check()')#debug
#atr= self.cc.card_get_ATR()
except Exception as e:
_logger.exception(f"Exception: {str(e)}")
Expand All @@ -221,9 +210,6 @@ def request(self, request_type, *args):
return None

def PIN_dialog(self, msg):
while self.ux_busy:
sleep(1)

while True:
password = self.handler.get_passphrase(msg, False)
if password is None:
Expand Down Expand Up @@ -347,10 +333,10 @@ def sign_message(self, sequence, message, password, *, script_type=None):
finally:
_logger.info(f"[Satochip_KeyStore] sign_message: finally")
self.handler.finished()


def sign_transaction(self, tx, password):
_logger.info(f"In sign_transaction(): tx: {str(tx)}")
_logger.info(f"In sign_transaction(): tx: {str(tx)}")
client = self.get_client()
is_ok = client.verify_PIN()
segwitTransaction = False
Expand All @@ -364,8 +350,8 @@ def sign_transaction(self, tx, password):
txOutputs += script
#txOutputs = bfh(txOutputs)
hashOutputs = sha256d(bfh(txOutputs)).hex()
_logger.info(f"In sign_transaction(): hashOutputs= {hashOutputs}")
_logger.info(f"In sign_transaction(): outputs= {txOutputs}")
_logger.info(f"In sign_transaction(): hashOutputs= {hashOutputs}")
_logger.info(f"In sign_transaction(): outputs= {txOutputs}")

# Fetch inputs of the transaction to sign
for i,txin in enumerate(tx.inputs()):
Expand Down Expand Up @@ -624,9 +610,9 @@ def _import_seed(self, settings, device_id, handler):
client = devmgr.client_by_id(device_id)
if not client:
raise Exception(_("The device was disconnected."))

label, seed, passphrase = settings

# check seed validity
(is_checksum_valid, is_wordlist_valid) = bip39_is_checksum_valid(seed)
if is_checksum_valid and is_wordlist_valid:
Expand All @@ -636,7 +622,7 @@ def _import_seed(self, settings, device_id, handler):
else:
_logger.error(f"[SatochipPlugin] _import_seed() wrong seed format!")
raise Exception('Wrong BIP39 mnemonic format!')

# verify pin:
is_ok = client.verify_PIN()

Expand Down Expand Up @@ -668,13 +654,13 @@ def wizard_entry_for_device(self, device_info: 'DeviceInfo', *, new_wallet=True)
_logger.info(f"[SatochipPlugin] wizard_entry_for_device() device_info: {device_info}")
_logger.info(f"[SatochipPlugin] wizard_entry_for_device() new_wallet: {new_wallet}")

device_state = device_info.initialized # can be None, False or True.
device_state = device_info.initialized # can be None, False or True.
# None is used to distinguish a completely new card from a card where the seed has been reset, but the PIN is still set.
_logger.info(f"[SatochipPlugin] wizard_entry_for_device() device_state: {device_state}")
if new_wallet:
if device_state == None:
if device_state is None:
return 'satochip_not_setup'
elif device_state == False:
elif device_state is False:
return 'satochip_not_seeded'
else:
return 'satochip_start'
Expand Down

0 comments on commit 7193d88

Please sign in to comment.