1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-21 23:18:13 +00:00

style: apply black 20.8b1

This commit is contained in:
matejcik 2020-09-25 13:59:16 +02:00
parent 6dda240f5c
commit e4785d47e0
30 changed files with 183 additions and 62 deletions

View File

@ -8,7 +8,9 @@ def main(file: str = None):
config = configparser.ConfigParser()
config.read_file(open("hardware.cfg"))
t1 = TrezorOne(
config["t1"]["location"], config["t1"]["port"], config["t1"]["arduino_serial"],
config["t1"]["location"],
config["t1"]["port"],
config["t1"]["arduino_serial"],
)
t1.update_firmware(file)

View File

@ -21,7 +21,7 @@ if False:
_MAX_COORDINATOR_LEN = const(18)
async def authorize_coinjoin(ctx: wire.Context, msg: AuthorizeCoinJoin,) -> Success:
async def authorize_coinjoin(ctx: wire.Context, msg: AuthorizeCoinJoin) -> Success:
# We cannot use the @with_keychain decorator here, because we need the keychain
# to survive the function exit. The ownership of the keychain is transferred to
# the CoinJoinAuthorization object, which takes care of its destruction.

View File

@ -364,7 +364,8 @@ class Bitcoin:
if txi.script_type == InputScriptType.SPENDMULTISIG:
assert txi.multisig is not None # checked in sanitize_tx_input
script_pubkey = scripts.output_script_multisig(
multisig.multisig_get_pubkeys(txi.multisig), txi.multisig.m,
multisig.multisig_get_pubkeys(txi.multisig),
txi.multisig.m,
)
elif txi.script_type == InputScriptType.SPENDADDRESS:
script_pubkey = scripts.output_script_p2pkh(
@ -478,17 +479,26 @@ class Bitcoin:
return self.get_sighash_type(txi) & 0xFF
def write_tx_input(
self, w: writers.Writer, txi: Union[TxInput, PrevInput], script: bytes,
self,
w: writers.Writer,
txi: Union[TxInput, PrevInput],
script: bytes,
) -> None:
writers.write_tx_input(w, txi, script)
def write_tx_output(
self, w: writers.Writer, txo: Union[TxOutput, PrevOutput], script_pubkey: bytes,
self,
w: writers.Writer,
txo: Union[TxOutput, PrevOutput],
script_pubkey: bytes,
) -> None:
writers.write_tx_output(w, txo, script_pubkey)
def write_tx_header(
self, w: writers.Writer, tx: Union[SignTx, PrevTx], witness_marker: bool,
self,
w: writers.Writer,
tx: Union[SignTx, PrevTx],
witness_marker: bool,
) -> None:
writers.write_uint32(w, tx.version) # nVersion
if witness_marker:

View File

@ -62,7 +62,10 @@ class Bitcoinlike(Bitcoin):
return hashtype
def write_tx_header(
self, w: writers.Writer, tx: Union[SignTx, PrevTx], witness_marker: bool,
self,
w: writers.Writer,
tx: Union[SignTx, PrevTx],
witness_marker: bool,
) -> None:
writers.write_uint32(w, tx.version) # nVersion
if self.coin.timestamp:

View File

@ -155,7 +155,10 @@ class Decred(Bitcoin):
self.write_tx_output(self.h_prefix, txo, script_pubkey)
def write_tx_input(
self, w: writers.Writer, txi: Union[TxInput, PrevInput], script: bytes,
self,
w: writers.Writer,
txi: Union[TxInput, PrevInput],
script: bytes,
) -> None:
writers.write_bytes_reversed(w, txi.prev_hash, writers.TX_HASH_SIZE)
writers.write_uint32(w, txi.prev_index or 0)
@ -163,7 +166,10 @@ class Decred(Bitcoin):
writers.write_uint32(w, txi.sequence)
def write_tx_output(
self, w: writers.Writer, txo: Union[TxOutput, PrevOutput], script_pubkey: bytes,
self,
w: writers.Writer,
txo: Union[TxOutput, PrevOutput],
script_pubkey: bytes,
) -> None:
writers.write_uint64(w, txo.amount)
if isinstance(txo, PrevOutput):
@ -175,7 +181,10 @@ class Decred(Bitcoin):
writers.write_bytes_prefixed(w, script_pubkey)
def write_tx_header(
self, w: writers.Writer, tx: Union[SignTx, PrevTx], witness_marker: bool,
self,
w: writers.Writer,
tx: Union[SignTx, PrevTx],
witness_marker: bool,
) -> None:
# The upper 16 bits of the transaction version specify the serialization
# format and the lower 16 bits specify the version number.

View File

@ -38,7 +38,7 @@ def write_bytes_prefixed(w: Writer, b: bytes) -> None:
write_bytes_unchecked(w, b)
def write_tx_input(w: Writer, i: Union[TxInput, PrevInput], script: bytes,) -> None:
def write_tx_input(w: Writer, i: Union[TxInput, PrevInput], script: bytes) -> None:
write_bytes_reversed(w, i.prev_hash, TX_HASH_SIZE)
write_uint32(w, i.prev_index)
write_bytes_prefixed(w, script)

View File

@ -196,7 +196,9 @@ def _derive_byron_address(
def _derive_shelley_address(
keychain: seed.Keychain, parameters: CardanoAddressParametersType, network_id: int,
keychain: seed.Keychain,
parameters: CardanoAddressParametersType,
network_id: int,
) -> bytes:
if not is_shelley_path(parameters.address_n):
raise wire.DataError("Invalid path for shelley address!")
@ -213,7 +215,10 @@ def _derive_shelley_address(
address = _derive_enterprise_address(keychain, parameters.address_n, network_id)
elif parameters.address_type == CardanoAddressType.POINTER:
address = _derive_pointer_address(
keychain, parameters.address_n, parameters.certificate_pointer, network_id,
keychain,
parameters.address_n,
parameters.certificate_pointer,
network_id,
)
elif parameters.address_type == CardanoAddressType.REWARD:
address = _derive_reward_address(keychain, parameters.address_n, network_id)
@ -249,7 +254,8 @@ def _derive_base_address(
def _validate_base_address_staking_info(
staking_path: List[int], staking_key_hash: bytes,
staking_path: List[int],
staking_key_hash: bytes,
) -> None:
if (staking_key_hash is None) == (not staking_path):
raise wire.DataError(
@ -311,7 +317,9 @@ def _encode_certificate_pointer(pointer: CardanoBlockchainPointerType) -> bytes:
def _derive_enterprise_address(
keychain: seed.Keychain, path: List[int], network_id: int,
keychain: seed.Keychain,
path: List[int],
network_id: int,
) -> bytes:
header = _create_address_header(CardanoAddressType.ENTERPRISE, network_id)
spending_key_hash = get_public_key_hash(keychain, path)
@ -320,7 +328,9 @@ def _derive_enterprise_address(
def _derive_reward_address(
keychain: seed.Keychain, path: List[int], network_id: int,
keychain: seed.Keychain,
path: List[int],
network_id: int,
) -> bytes:
if not is_staking_path(path):
raise wire.DataError("Invalid path for reward address!")

View File

@ -20,7 +20,11 @@ async def get_public_key(
ctx: wire.Context, msg: CardanoGetPublicKey, keychain: seed.Keychain
):
await paths.validate_path(
ctx, _validate_path_for_get_public_key, keychain, msg.address_n, CURVE,
ctx,
_validate_path_for_get_public_key,
keychain,
msg.address_n,
CURVE,
)
try:

View File

@ -80,7 +80,9 @@ async def show_warning_tx_no_staking_info(
async def show_warning_tx_pointer_address(
ctx: wire.Context, pointer: CardanoBlockchainPointerType, amount: int,
ctx: wire.Context,
pointer: CardanoBlockchainPointerType,
amount: int,
):
page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
page1.normal("Change address has a")
@ -100,7 +102,9 @@ async def show_warning_tx_pointer_address(
async def show_warning_tx_different_staking_account(
ctx: wire.Context, staking_account_path: List[int], amount: int,
ctx: wire.Context,
staking_account_path: List[int],
amount: int,
):
page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
page1.normal("Change address staking")
@ -117,7 +121,9 @@ async def show_warning_tx_different_staking_account(
async def show_warning_tx_staking_key_hash(
ctx: wire.Context, staking_key_hash: bytes, amount: int,
ctx: wire.Context,
staking_key_hash: bytes,
amount: int,
):
page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
page1.normal("Change address staking")
@ -282,7 +288,9 @@ async def show_warning_address_foreign_staking_key(
staking_key_message = ("Staking key:", hexlify(staking_key_hash).decode())
await show_warning(
ctx, staking_key_message, button="Ok",
ctx,
staking_key_message,
button="Ok",
)

View File

@ -286,7 +286,8 @@ def _build_withdrawals(
reward_address = derive_address_bytes(
keychain,
CardanoAddressParametersType(
address_type=CardanoAddressType.REWARD, address_n=withdrawal.path,
address_type=CardanoAddressType.REWARD,
address_n=withdrawal.path,
),
protocol_magic,
network_id,
@ -465,16 +466,22 @@ async def _show_change_output_staking_warnings(
await show_warning_tx_no_staking_info(ctx, address_type, amount)
elif staking_use_case == staking_use_cases.POINTER_ADDRESS:
await show_warning_tx_pointer_address(
ctx, address_parameters.certificate_pointer, amount,
ctx,
address_parameters.certificate_pointer,
amount,
)
elif staking_use_case == staking_use_cases.MISMATCH:
if address_parameters.address_n_staking:
await show_warning_tx_different_staking_account(
ctx, to_account_path(address_parameters.address_n_staking), amount,
ctx,
to_account_path(address_parameters.address_n_staking),
amount,
)
else:
await show_warning_tx_staking_key_hash(
ctx, address_parameters.staking_key_hash, amount,
ctx,
address_parameters.staking_key_hash,
amount,
)

View File

@ -113,7 +113,10 @@ class Keychain:
raise FORBIDDEN_KEY_PATH
def _derive_with_cache(
self, prefix_len: int, path: paths.PathType, new_root: Callable[[], NodeType],
self,
prefix_len: int,
path: paths.PathType,
new_root: Callable[[], NodeType],
) -> NodeType:
cached_prefix = tuple(path[:prefix_len])
cached_root = self._cache.get(cached_prefix) # type: Optional[NodeType]
@ -141,7 +144,9 @@ class Keychain:
raise FORBIDDEN_KEY_PATH
return self._derive_with_cache(
prefix_len=1, path=path, new_root=lambda: Slip21Node(seed=self.seed),
prefix_len=1,
path=path,
new_root=lambda: Slip21Node(seed=self.seed),
)
def __enter__(self) -> "Keychain":

View File

@ -153,7 +153,7 @@ async def require_confirm_change_autolock_delay(ctx, delay_ms):
await require_confirm(ctx, text, ButtonRequestType.ProtectCall)
async def require_confirm_safety_checks(ctx, level: EnumTypeSafetyCheckLevel,) -> None:
async def require_confirm_safety_checks(ctx, level: EnumTypeSafetyCheckLevel) -> None:
if level == SafetyCheckLevel.PromptAlways:
text = Text("Safety override", ui.ICON_CONFIG)
text.normal(

View File

@ -55,7 +55,9 @@ async def all_outputs_set(state: State) -> MoneroTransactionAllOutSetAck:
# Initializes RCTsig structure (fee, tx prefix hash, type)
rv_pb = MoneroRingCtSig(
txn_fee=state.fee, message=state.tx_prefix_hash, rv_type=state.tx_type,
txn_fee=state.fee,
message=state.tx_prefix_hash,
rv_type=state.tx_type,
)
_out_pk(state)

View File

@ -198,7 +198,9 @@ def sign_tx(
and cannot be overriden by kwargs.
"""
signtx = messages.SignTx(
coin_name=coin_name, inputs_count=len(inputs), outputs_count=len(outputs),
coin_name=coin_name,
inputs_count=len(inputs),
outputs_count=len(outputs),
)
for name, value in kwargs.items():
if hasattr(signtx, name):

View File

@ -152,7 +152,8 @@ def create_certificate(certificate) -> messages.CardanoTxCertificateType:
or certificate_type == messages.CardanoCertificateType.STAKE_DEREGISTRATION
):
return messages.CardanoTxCertificateType(
type=certificate_type, path=tools.parse_path(path),
type=certificate_type,
path=tools.parse_path(path),
)
else:
raise ValueError("Unknown certificate type")
@ -164,7 +165,8 @@ def create_withdrawal(withdrawal) -> messages.CardanoTxWithdrawalType:
path = withdrawal["path"]
return messages.CardanoTxWithdrawalType(
path=tools.parse_path(path), amount=int(withdrawal["amount"]),
path=tools.parse_path(path),
amount=int(withdrawal["amount"]),
)

View File

@ -145,7 +145,10 @@ def configure_logging(verbose: int):
"-j", "--json", "is_json", is_flag=True, help="Print result as JSON object"
)
@click.option(
"-P", "--passphrase-on-host", is_flag=True, help="Enter passphrase on host.",
"-P",
"--passphrase-on-host",
is_flag=True,
help="Enter passphrase on host.",
)
@click.option(
"-s",

View File

@ -83,7 +83,10 @@ class TrezorClient:
"""
def __init__(
self, transport, ui, session_id=None,
self,
transport,
ui,
session_id=None,
):
LOG.info("creating client instance for device: {}".format(transport.get_path()))
self.transport = transport
@ -326,7 +329,9 @@ class TrezorClient:
@tools.expect(messages.Success, field="message")
def ping(
self, msg, button_protection=False,
self,
msg,
button_protection=False,
):
# We would like ping to work on any valid TrezorClient instance, but
# due to the protection modes, we need to go through self.call, and that will
@ -345,7 +350,7 @@ class TrezorClient:
finally:
self.close()
msg = messages.Ping(message=msg, button_protection=button_protection,)
msg = messages.Ping(message=msg, button_protection=button_protection)
return self.call(msg)
def get_device_id(self):

View File

@ -110,8 +110,8 @@ def verify(
def pubkey_from_privkey(privkey: Ed25519PrivateKey) -> Ed25519PublicPoint:
"""Interpret 32 bytes of data as an Ed25519 private key.
Calculate and return the corresponding public key.
"""
Calculate and return the corresponding public key.
"""
return Ed25519PublicPoint(_ed25519.publickey_unsafe(privkey))

View File

@ -397,7 +397,9 @@ def validate_code_hashes(fw: c.Container, version: FirmwareFormat) -> None:
def validate_onev2(fw: c.Container, allow_unsigned: bool = False) -> None:
try:
check_sig_v1(
digest_onev2(fw), fw.header.v1_key_indexes, fw.header.v1_signatures,
digest_onev2(fw),
fw.header.v1_key_indexes,
fw.header.v1_signatures,
)
except Unsigned:
if not allow_unsigned:

View File

@ -67,11 +67,11 @@ class PinButton(QPushButton):
class PinMatrixWidget(QWidget):
"""
Displays widget with nine blank buttons and password box.
Encodes button clicks into sequence of numbers for passing
into PinAck messages of Trezor.
Displays widget with nine blank buttons and password box.
Encodes button clicks into sequence of numbers for passing
into PinAck messages of Trezor.
show_strength=True may be useful for entering new PIN
show_strength=True may be useful for entering new PIN
"""
def __init__(self, show_strength=True, parent=None):
@ -142,7 +142,7 @@ class PinMatrixWidget(QWidget):
if __name__ == "__main__":
"""
Demo application showing PinMatrix widget in action
Demo application showing PinMatrix widget in action
"""
app = QApplication(sys.argv)

View File

@ -54,8 +54,7 @@ DEFAULT_NETWORK_PASSPHRASE = "Public Global Stellar Network ; September 2015"
def address_from_public_key(pk_bytes):
"""Returns the base32-encoded version of pk_bytes (G...)
"""
"""Returns the base32-encoded version of pk_bytes (G...)"""
final_bytes = bytearray()
# version
@ -80,8 +79,8 @@ def address_to_public_key(address_str):
def parse_transaction_bytes(tx_bytes):
"""Parses base64data into a map with the following keys:
tx - a StellarSignTx describing the transaction header
operations - an array of protobuf message objects for each operation
tx - a StellarSignTx describing the transaction header
operations - an array of protobuf message objects for each operation
"""
tx = messages.StellarSignTx()
unpacker = xdrlib.Unpacker(tx_bytes)

View File

@ -19,7 +19,8 @@ def request_output(n, tx_hash=None):
def request_meta(tx_hash):
return messages.TxRequest(
request_type=T.TXMETA, details=messages.TxRequestDetailsType(tx_hash=tx_hash),
request_type=T.TXMETA,
details=messages.TxRequestDetailsType(tx_hash=tx_hash),
)

View File

@ -83,7 +83,8 @@ def test_apply_auto_lock_delay_valid(client, seconds):
@pytest.mark.skip_ui
@pytest.mark.parametrize(
"seconds", [0, 1, 9, 536871, 2 ** 22],
"seconds",
[0, 1, 9, 536871, 2 ** 22],
)
def test_apply_auto_lock_delay_out_of_range(client, seconds):
with client:

View File

@ -957,7 +957,11 @@ class TestMsgSigntx:
# Now run the attack, must trigger the exception
with pytest.raises(TrezorFailure) as exc:
btc.sign_tx(
client, "Testnet", [inp1], [out1, out2], prev_txes=TX_CACHE_TESTNET,
client,
"Testnet",
[inp1],
[out1, out2],
prev_txes=TX_CACHE_TESTNET,
)
assert exc.value.code == messages.FailureType.ProcessError

View File

@ -299,7 +299,11 @@ def test_p2wpkh_presigned(client):
# Test with second input as pre-signed external.
with client:
_, serialized_tx = btc.sign_tx(
client, "Testnet", [inp1, inp2], [out1, out2], prev_txes=TX_CACHE_TESTNET,
client,
"Testnet",
[inp1, inp2],
[out1, out2],
prev_txes=TX_CACHE_TESTNET,
)
assert (
@ -311,7 +315,11 @@ def test_p2wpkh_presigned(client):
inp2.witness[10] ^= 1
with pytest.raises(TrezorFailure, match="Invalid signature"):
btc.sign_tx(
client, "Testnet", [inp1, inp2], [out1, out2], prev_txes=TX_CACHE_TESTNET,
client,
"Testnet",
[inp1, inp2],
[out1, out2],
prev_txes=TX_CACHE_TESTNET,
)
@ -482,7 +490,11 @@ def test_p2wpkh_with_proof(client):
]
)
_, serialized_tx = btc.sign_tx(
client, "Testnet", [inp1, inp2], [out1, out2], prev_txes=TX_CACHE_TESTNET,
client,
"Testnet",
[inp1, inp2],
[out1, out2],
prev_txes=TX_CACHE_TESTNET,
)
assert (
@ -494,7 +506,11 @@ def test_p2wpkh_with_proof(client):
inp1.ownership_proof[10] ^= 1
with pytest.raises(TrezorFailure, match="Invalid signature"):
btc.sign_tx(
client, "Testnet", [inp1, inp2], [out1, out2], prev_txes=TX_CACHE_TESTNET,
client,
"Testnet",
[inp1, inp2],
[out1, out2],
prev_txes=TX_CACHE_TESTNET,
)
@ -551,5 +567,9 @@ def test_p2wpkh_with_false_proof(client):
with pytest.raises(TrezorFailure, match="Invalid external input"):
btc.sign_tx(
client, "Testnet", [inp1, inp2], [out1], prev_txes=TX_CACHE_TESTNET,
client,
"Testnet",
[inp1, inp2],
[out1],
prev_txes=TX_CACHE_TESTNET,
)

View File

@ -408,7 +408,11 @@ class TestMsgSigntxSegwit:
# "Fee over threshold" warning is displayed - fee is the whole TRUE_AMOUNT
client.set_expected_responses(expected_responses)
btc.sign_tx(
client, "Testnet", [inp1, inp2], [out1], prev_txes=TX_API,
client,
"Testnet",
[inp1, inp2],
[out1],
prev_txes=TX_API,
)
# In Phase 1 make the user confirm a lower value of the segwit input.
@ -427,7 +431,11 @@ class TestMsgSigntxSegwit:
with pytest.raises(TrezorFailure) as e, client:
client.set_expected_responses(expected_responses)
btc.sign_tx(
client, "Testnet", [inp1, inp2], [out1], prev_txes=TX_API,
client,
"Testnet",
[inp1, inp2],
[out1],
prev_txes=TX_API,
)
assert e.value.failure.message.endswith("Invalid amount specified")

View File

@ -159,7 +159,12 @@ class TestMsgSigntxZcash:
with pytest.raises(TrezorFailure, match="Version group ID must be set."):
btc.sign_tx(
client, "Zcash Testnet", [inp1], [out1], version=4, prev_txes=TX_API,
client,
"Zcash Testnet",
[inp1],
[out1],
version=4,
prev_txes=TX_API,
)
def test_spend_old_versions(self, client):

View File

@ -83,7 +83,10 @@ class EmulatorWrapper:
if gen == "legacy":
self.emulator = LegacyEmulator(
executable, self.profile_dir.name, storage=storage, headless=True,
executable,
self.profile_dir.name,
storage=storage,
headless=True,
)
elif gen == "core":
self.emulator = CoreEmulator(

View File

@ -178,7 +178,11 @@ def create_reports():
"Folder does not exist, has it been recorded?", current_screens
)
diff(
master_screens, current_screens, test_name, master_hash, current_hash,
master_screens,
current_screens,
test_name,
master_hash,
current_hash,
)

View File

@ -46,7 +46,9 @@ def emulator(gen, tag):
with EmulatorWrapper(gen, tag) as emu:
# set up a passphrase-protected device
device.reset(
emu.client, pin_protection=False, skip_backup=True,
emu.client,
pin_protection=False,
skip_backup=True,
)
resp = emu.client.call(
ApplySettingsCompat(use_passphrase=True, passphrase_source=SOURCE_HOST)