1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2025-03-19 01:26:06 +00:00

style(python): update trezorlib.firmware to new-style type annotations

[no changelog]
This commit is contained in:
matejcik 2025-01-20 11:39:04 +01:00 committed by matejcik
parent 72d14a370c
commit fcb76df9f5
6 changed files with 40 additions and 30 deletions

View File

@ -14,6 +14,8 @@
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
from __future__ import annotations
import typing as t
from hashlib import blake2s
@ -21,9 +23,9 @@ from typing_extensions import Protocol, TypeGuard
from .. import messages
from ..tools import session
from .models import Model
from .core import VendorFirmware
from .legacy import LegacyFirmware, LegacyV2Firmware
from .models import Model
# re-exports:
if True:
@ -45,7 +47,7 @@ if t.TYPE_CHECKING:
class FirmwareType(Protocol):
@classmethod
def parse(cls: t.Type[T], data: bytes) -> T: ...
def parse(cls: type[T], data: bytes) -> T: ...
def verify(self, dev_keys: bool = False) -> None: ...
@ -54,7 +56,7 @@ if t.TYPE_CHECKING:
def model(self) -> Model | None: ...
def parse(data: bytes) -> "FirmwareType":
def parse(data: bytes) -> FirmwareType:
try:
if data[:4] == b"TRZR":
return LegacyFirmware.parse(data)
@ -68,7 +70,7 @@ def parse(data: bytes) -> "FirmwareType":
raise FirmwareIntegrityError("Invalid firmware image") from e
def is_onev2(fw: "FirmwareType") -> TypeGuard[LegacyFirmware]:
def is_onev2(fw: FirmwareType) -> TypeGuard[LegacyFirmware]:
return isinstance(fw, LegacyFirmware) and fw.embedded_v2 is not None
@ -77,7 +79,7 @@ def is_onev2(fw: "FirmwareType") -> TypeGuard[LegacyFirmware]:
@session
def update(
client: "TrezorClient",
client: TrezorClient,
data: bytes,
progress_update: t.Callable[[int], t.Any] = lambda _: None,
):
@ -109,7 +111,7 @@ def update(
raise RuntimeError(f"Unexpected message {resp}")
def get_hash(client: "TrezorClient", challenge: t.Optional[bytes]) -> bytes:
def get_hash(client: TrezorClient, challenge: bytes | None) -> bytes:
return client.call(
messages.GetFirmwareHash(challenge=challenge), expect=messages.FirmwareHash
).hash

View File

@ -14,7 +14,8 @@
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
import typing as t
from __future__ import annotations
from copy import copy
from enum import Enum
@ -45,15 +46,15 @@ class FirmwareHeader(Struct):
header_len: int
expiry: int
code_length: int
version: t.Tuple[int, int, int, int]
fix_version: t.Tuple[int, int, int, int]
hw_model: t.Union[Model, bytes]
version: tuple[int, int, int, int]
fix_version: tuple[int, int, int, int]
hw_model: Model | bytes
hw_revision: int
monotonic: int
hashes: t.List[bytes]
hashes: list[bytes]
v1_signatures: t.List[bytes]
v1_key_indexes: t.List[int]
v1_signatures: list[bytes]
v1_key_indexes: list[int]
sigmask: int
signature: bytes
@ -118,10 +119,10 @@ class FirmwareImage(Struct):
c.Terminated,
)
def get_hash_params(self) -> "util.FirmwareHashParameters":
def get_hash_params(self) -> util.FirmwareHashParameters:
return Model.from_hw_model(self.header.hw_model).hash_params()
def code_hashes(self) -> t.List[bytes]:
def code_hashes(self) -> list[bytes]:
"""Calculate hashes of chunks of `code`.
Assume that the first `code_offset` bytes of `code` are taken up by the header.
@ -154,7 +155,6 @@ class FirmwareImage(Struct):
raise util.FirmwareIntegrityError("Invalid firmware data.")
def digest(self) -> bytes:
hash_params = self.get_hash_params()
header = copy(self.header)

View File

@ -14,6 +14,8 @@
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
from __future__ import annotations
import hashlib
import typing as t
from dataclasses import field
@ -101,7 +103,7 @@ class LegacyV2Firmware(FirmwareImage):
V3_FIRST_VERSION = (1, 12, 0)
def get_hash_params(self) -> "util.FirmwareHashParameters":
def get_hash_params(self) -> util.FirmwareHashParameters:
return Model.ONE.hash_params()
def verify_v2(self, dev_keys: bool) -> None:
@ -160,11 +162,11 @@ class LegacyFirmware(Struct):
expected format of firmware binary for Trezor One version 1.8.0, which can be installed
by both the older and the newer bootloader."""
key_indexes: t.List[int]
signatures: t.List[bytes]
key_indexes: list[int]
signatures: list[bytes]
code: bytes
flags: t.Dict[str, t.Any] = field(default_factory=dict)
embedded_v2: t.Optional[LegacyV2Firmware] = subcon(LegacyV2Firmware, default=None)
flags: dict[str, t.Any] = field(default_factory=dict)
embedded_v2: LegacyV2Firmware | None = subcon(LegacyV2Firmware, default=None)
# fmt: off
SUBCON = c.Struct(

View File

@ -14,6 +14,8 @@
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
from __future__ import annotations
import hashlib
import typing as t
from dataclasses import dataclass
@ -45,7 +47,7 @@ class Model(Enum):
DISC2 = b"D002"
@classmethod
def from_hw_model(cls, hw_model: t.Union["Self", bytes]) -> "Model":
def from_hw_model(cls, hw_model: Self | bytes) -> Model:
if isinstance(hw_model, cls):
return hw_model
if hw_model == b"\x00\x00\x00\x00":
@ -53,17 +55,17 @@ class Model(Enum):
raise ValueError(f"Unknown hardware model: {hw_model}")
@classmethod
def from_trezor_model(cls, trezor_model: "TrezorModel") -> "Self":
def from_trezor_model(cls, trezor_model: TrezorModel) -> Self:
return cls(trezor_model.internal_name.encode("ascii"))
def model_keys(self, dev_keys: bool = False) -> "ModelKeys":
def model_keys(self, dev_keys: bool = False) -> ModelKeys:
if dev_keys:
model_map = MODEL_MAP_DEV
else:
model_map = MODEL_MAP
return model_map[self]
def hash_params(self) -> "FirmwareHashParameters":
def hash_params(self) -> FirmwareHashParameters:
return MODEL_HASH_PARAMS_MAP[self]

View File

@ -14,6 +14,8 @@
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
from __future__ import annotations
import typing as t
from dataclasses import dataclass
@ -45,4 +47,4 @@ Hasher = t.Callable[[bytes], DigestCalculator]
class FirmwareHashParameters:
hash_function: Hasher
chunk_size: int
padding_byte: t.Optional[bytes]
padding_byte: bytes | None

View File

@ -14,6 +14,8 @@
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
from __future__ import annotations
import hashlib
import typing as t
from copy import copy
@ -85,13 +87,13 @@ class VendorTrust(Struct):
class VendorHeader(Struct):
header_len: int
expiry: int
version: t.Tuple[int, int]
version: tuple[int, int]
sig_m: int
# sig_n: int
hw_model: t.Union[Model, bytes]
pubkeys: t.List[bytes]
hw_model: Model | bytes
pubkeys: list[bytes]
text: str
image: t.Dict[str, t.Any]
image: dict[str, t.Any]
sigmask: int
signature: bytes