Skip to content

Conversation

@somebodyLi
Copy link
Contributor

@somebodyLi somebodyLi commented Mar 3, 2025

Summary by CodeRabbit

  • New Features

    • Expanded support for extra networks and tokens—including new chains such as HashKey Chain and Data Trade Chain.
    • Introduced advanced signature capabilities for Bitcoin (PSBT) and Solana (off‐chain and unsafe message signing).
    • Enhanced Cardano functionality with updated vote registration and certificate types.
  • User Interface & Localization

    • Revamped UI layouts, auto‑lock/shutdown settings, and confirmation prompts (including EIP‑712 warnings) for improved usability.
    • Updated on‑device messaging and added full Brazilian Portuguese support alongside other language improvements.
  • Security Enhancements

    • Improved key derivation and authentication workflows to strengthen overall device security.

@somebodyLi somebodyLi requested a review from a team as a code owner March 3, 2025 07:35
@coderabbitai
Copy link

coderabbitai bot commented Mar 3, 2025

Walkthrough

The update spans numerous modules and protocols. It introduces new message types and functions for Bitcoin PSBT signing, Cardano CVote registration, Solana off‐chain/unsafe signing, and TON signature output. Several files have been refactored for clearer key derivation and path validation (with a new force_strict parameter). UI elements, bootloader layouts, and localization strings have been revised across multiple languages (including new Brazilian Portuguese support). CLI commands now expose additional options for signing and address retrieval. Renamed constants and enums further align the code with updated protocol specifications.

Changes

File(s) Change Summary
common/defs/ethereum/chains Updated subproject commit ID.
common/defs/evm_tokens/1.json, 177.json, 9798.json Added new token entries and JSON definitions for Ethereum Mainnet, HashKey Chain, and Data Trade Chain.
common/defs/support.json Inserted new token definitions and renamed existing tokens under Ethereum (ERC20) networks.
common/protob/messages-*.proto Added new protobuf messages and enums for Bitcoin PSBT, Cardano, and Solana. Also, updated SignMessage to include additional fields.
core/embed/bootloader/bootui.*, icon_onekey.h, main.c, version.h Renamed UI functions (e.g., ui_logo_center → ui_logo_onekey, ui_title_update → ui_statusbar_update), adjusted layout constants, and updated firmware version to 4.10.0.
core/src/all_modules.py Added new module imports for Bitcoin PSBT, Solana message signing, and Cardano enum enhancements.
core/src/apps/bitcoin/**.py Introduced Bitcoin PSBT handling: new functions for creating transactions (bip322_simple), key and script handling, serialization, and revised sign_message/sign_taproot flows.
core/src/apps/cardano/**.py Extensive Cardano updates including new certificate types (STAKE_REGISTRATION_CONWAY, etc.), CVote registration, refined address validation, UI layout adjustments, and helper refactoring.
core/src/apps/solana/**.proto, sign_offchain_message.py, sign_unsafe_message.py Added new Solana message types and signing functions to support off-chain and unsafe message signing.
core/src/apps/ethereum/onekey/**.py Updated Ethereum modules with new network entries, token mapping updates, and improved path validation with force_strict=False.
core/src/apps/ton/**.py Changed TON functions’ return types from bytes to dictionaries containing signature and signing message details.
core/src/trezor/enums/**.py, messages.py Expanded enums and messages for Cardano (e.g. CVote registration) and Solana, renaming several constants accordingly.
core/src/trezor/lvglui/i18n/** Updated and added localization strings across multiple languages; added pt_BR support and refined UI text.
python/src/trezorlib/cli/** Enhanced CLI commands for Cardano, Solana, and TON; added new options (e.g., chunkify, tag_cbor_sets) and updated path help text.
python/src/trezorlib/cardano.py Shifted from governance registration to CVote registration; added parameters (chunkify, tag_cbor_sets) and updated certificate parsing logic.
tools/i18n.py Extended language support by including Portuguese (Brazil) in SUPPORTED_LANGS and LANG_MAP.
core/src/trezor/utils.py, uart.py Added new methods (append, extend, tell) for buffer management and updated LCD/ BLE handling logic.
core/src/trezor/lvglui/scrs/** Adjusted home screen and template layouts; introduced new confirmation screens (e.g. EIP712Warning, confirm_sol_message) with extra warning options.

Sequence Diagram(s)

Bitcoin PSBT Signing Flow

sequenceDiagram
    participant H as Host
    participant D as Device
    participant PSBT as Bitcoin PSBT Module

    H->>D: Send SignPsbt message with PSBT data
    D-->>PSBT: Process transaction, validate key path (force_strict)
    PSBT-->>D: Generate signature for PSBT inputs
    D->>H: Return SignedPsbt message with signed PSBT
Loading

Solana Off-Chain Message Signing Flow

sequenceDiagram
    participant H as Host
    participant D as Device
    participant MSG as Solana Message Module

    H->>D: Send SolanaSignOffChainMessage with address and message metadata
    D->>H: (Optionally) Display message for confirmation
    D-->>MSG: Derive key (force_strict=False) and sign off-chain message
    MSG-->>D: Create signature and package into SolanaMessageSignature
    D->>H: Return SolanaMessageSignature with signature and public key
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or Summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

🛑 Comments failed to post (142)
core/src/trezor/utils.py (2)

113-127: 🧹 Nitpick (assertive)

Simplify the conditional expression for better readability.

The ternary expression is nested and hard to follow. The static analyzer correctly flagged this.

-            timeout_ms=(SHORT_AUTO_LOCK_TIME_MS if not timeouts_ms else timeouts_ms)
+            timeout_ms=(timeouts_ms if timeouts_ms else SHORT_AUTO_LOCK_TIME_MS)
             if not config.is_unlocked()
-            else None
+            else None,

Note: I also added the trailing comma at the end for consistency with the codebase style.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

def lcd_resume(timeouts_ms: int | None = None) -> bool:
    from trezor.ui import display
    from storage import device
    from apps import base
    from trezor import config

    if display.backlight() != device.get_brightness() or timeouts_ms:
        global AUTO_POWER_OFF
        display.backlight(device.get_brightness())
        AUTO_POWER_OFF = False
        base.reload_settings_from_storage(
            timeout_ms=(timeouts_ms if timeouts_ms else SHORT_AUTO_LOCK_TIME_MS)
            if not config.is_unlocked()
            else None,
        )
🧰 Tools
🪛 Ruff (0.8.2)

124-124: Use timeouts_ms if timeouts_ms else SHORT_AUTO_LOCK_TIME_MS instead of SHORT_AUTO_LOCK_TIME_MS if not timeouts_ms else timeouts_ms

Replace with timeouts_ms if timeouts_ms else SHORT_AUTO_LOCK_TIME_MS

(SIM212)


126-126: Trailing comma missing

Add trailing comma

(COM812)


372-375: 🛠️ Refactor suggestion

Add bounds checking to prevent buffer overflow.

The append method directly modifies the buffer without checking if we're at the end of the buffer.

def append(self, b: int) -> None:
+    if self.offset >= len(self.buffer):
+        raise EOFError
    self.buffer[self.offset] = b
    self.offset += 1
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def append(self, b: int) -> None:
        if self.offset >= len(self.buffer):
            raise EOFError
        self.buffer[self.offset] = b
        self.offset += 1
core/src/apps/polkadot/seed.py (2)

39-41: ⚠️ Potential issue

The boolean parameter is unused.

You added a new parameter _force_strict but it doesn't affect the function's behavior since it's never referenced in the function body.

Either use the parameter or remove it:

-    def verify_path(self, path: Bip32Path, _force_strict: bool = True) -> None:
+    def verify_path(self, path: Bip32Path) -> None:
         if not self.is_in_keychain(path):
             raise wire.DataError("Forbidden key path")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def verify_path(self, path: Bip32Path) -> None:
        if not self.is_in_keychain(path):
            raise wire.DataError("Forbidden key path")
🧰 Tools
🪛 Ruff (0.8.2)

39-39: Boolean-typed positional argument in function definition

(FBT001)


39-39: Boolean default positional argument in function definition

(FBT002)


41-41: Avoid specifying long messages outside the exception class

(TRY003)


39-39: 🛠️ Refactor suggestion

Fix boolean parameter to improve code clarity.

The added _force_strict parameter has two issues:

  1. It's unused within the method but changes the API
  2. Boolean parameters make code harder to read at call sites

Use keyword arguments instead:

-    def verify_path(self, path: Bip32Path, _force_strict: bool = True) -> None:
+    def verify_path(self, path: Bip32Path, *, force_strict: bool = True) -> None:

Then update the method to actually use this parameter:

     def verify_path(self, path: Bip32Path, *, force_strict: bool = True) -> None:
-        if not self.is_in_keychain(path):
+        if force_strict and not self.is_in_keychain(path):
             raise wire.DataError("Forbidden key path")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def verify_path(self, path: Bip32Path, *, force_strict: bool = True) -> None:
        if force_strict and not self.is_in_keychain(path):
            raise wire.DataError("Forbidden key path")
🧰 Tools
🪛 Ruff (0.8.2)

39-39: Boolean-typed positional argument in function definition

(FBT001)


39-39: Boolean default positional argument in function definition

(FBT002)

core/src/trezor/ui/layouts/lvgl/__init__.py (3)

941-941: 🧹 Nitpick (assertive)

**New parameter adds flexibility while maintaining backward compatibility. **

Adding the is_standard parameter with a default value of True is a good approach for extending functionality without breaking existing callers.

Consider using keyword-only arguments for boolean parameters to make call sites more explicit:

-async def confirm_signverify(
-    ctx: wire.GenericContext,
-    coin: str,
-    message: str,
-    address: str,
-    verify: bool,
-    evm_chain_id: int | None = None,
-    title: str | None = None,
-    is_standard: bool = True,
+async def confirm_signverify(
+    ctx: wire.GenericContext,
+    coin: str,
+    message: str,
+    address: str,
+    verify: bool,
+    evm_chain_id: int | None = None,
+    title: str | None = None,
+    *, is_standard: bool = True,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

async def confirm_signverify(
    ctx: wire.GenericContext,
    coin: str,
    message: str,
    address: str,
    verify: bool,
    evm_chain_id: int | None = None,
    title: str | None = None,
    *, is_standard: bool = True,
):
    # Function body remains unchanged.
    pass
🧰 Tools
🪛 Ruff (0.8.2)

941-941: Boolean-typed positional argument in function definition

(FBT001)


941-941: Boolean default positional argument in function definition

(FBT002)


1242-1268: 🧹 Nitpick (assertive)

**New Solana message confirmation screen implementation follows best practices. **

The function properly handles both standard and unsafe Solana messages with appropriate warning banners when needed. Good pattern matching with other confirmation functions.

Similar to the earlier comment, consider making the boolean parameter keyword-only:

-async def confirm_sol_message(
-    ctx: wire.GenericContext,
-    address: str,
-    app_domain_fd: str | None,
-    message: str,
-    is_unsafe: bool = False,
+async def confirm_sol_message(
+    ctx: wire.GenericContext,
+    address: str,
+    app_domain_fd: str | None,
+    message: str,
+    *, is_unsafe: bool = False,

Also add trailing commas at function call sites for consistency and better future diffs.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

async def confirm_sol_message(
    ctx: wire.GenericContext,
    address: str,
    app_domain_fd: str | None,
    message: str,
    *, is_unsafe: bool = False,
) -> None:
    from trezor.lvglui.scrs.template import Message

    screen = Message(
        _(i18n_keys.TITLE__SIGN_STR_MESSAGE).format("SOL"),
        address,
        message,
        ctx.primary_color,
        ctx.icon_path,
        False,
        item_other=app_domain_fd,
        item_other_title="Application Domain:" if app_domain_fd else None,
        is_standard=not is_unsafe,
        warning_banner_text=_(i18n_keys.SECURITY__SOLANA_RAW_SIGNING_TX_WARNING)
        if is_unsafe
        else None,
    )
    await raise_if_cancelled(
        interact(ctx, screen, "confirm_sol_message", ButtonRequestType.ProtectCall)
    )
🧰 Tools
🪛 Ruff (0.8.2)

1247-1247: Boolean-typed positional argument in function definition

(FBT001)


1247-1247: Boolean default positional argument in function definition

(FBT002)


1257-1257: Boolean positional value in function call

(FBT003)


1266-1266: Trailing comma missing

Add trailing comma

(COM812)


1128-1144: 🧹 Nitpick (assertive)

**New EIP712 warning screen implementation looks good. **

Well-structured function that follows the established patterns for confirmation screens. The function properly handles warning levels and displays appropriate UI elements.

Add trailing commas to the function call for better diff readability when parameters change in the future:

await raise_if_cancelled(
    interact(
        ctx, 
        screen, 
        "confirm_eip712_warning", 
-       ButtonRequestType.ProtectCall
+       ButtonRequestType.ProtectCall,
    )
)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

async def confirm_eip712_warning(
    ctx: wire.GenericContext, primary_type: str, warning_level: int, text: str
) -> None:
    from trezor.lvglui.scrs.template import EIP712Warning

    screen = EIP712Warning(
        _(i18n_keys.TITLE__STR_TYPED_DATA).format(ctx.name),
        warning_level,
        text,
        primary_type,
        ctx.primary_color,
        ctx.icon_path,
    )
    await raise_if_cancelled(
        interact(
            ctx,
            screen,
            "confirm_eip712_warning",
            ButtonRequestType.ProtectCall,
        )
    )
🧰 Tools
🪛 Ruff (0.8.2)

1129-1129: Trailing comma missing

Add trailing comma

(COM812)


1142-1142: Trailing comma missing

Add trailing comma

(COM812)

core/src/trezor/strings.py (1)

96-96: 🧹 Nitpick (assertive)

Move import to the top of the file

Importing modules inside functions can slow code execution. Unless you need to avoid circular imports, move this import to the file header.

2 from micropython import const
3+from apps.common import signverify
4 

Committable suggestion skipped: line range outside the PR's diff.

core/src/apps/ethereum/networks.py.mako (1)

89-96: 🧹 Nitpick (assertive)

💡 Verification agent

🧩 Analysis chain

Consider moving DTT network to the template system

This hard-coded network entry bypasses the template generation system. While it works, it creates a maintenance risk if the template is regenerated.

Consider adding this network to the data source that feeds the template system rather than hard-coding it here.


🏁 Script executed:

#!/bin/bash
# Check how other networks are added in the repository
grep -r "yield" --include="*.mako" core/src/apps/ | grep -v "networks.py.mako"

Length of output: 228


Action Required: Migrate DTT Network to Template System

The DTT network in core/src/apps/ethereum/networks.py.mako is directly hard-coded. We checked similar yield constructs in other modules (like in core/src/apps/ethereum/tokens.py.mako and core/src/apps/nem/mosaic/nem_mosaics.py.mako), and they use the template data source. To reduce maintenance risk, please move the DTT entry into the template system.

  • Location: core/src/apps/ethereum/networks.py.mako, Lines 89-96
  • Suggestion: Use the data source that feeds your template system instead of hard-coding values.
core/src/apps/common/signverify.py (1)

34-41: 🧹 Nitpick (assertive)

Use an else block for better code structure

The code works but could be more clearly structured with an else block.

def decode_message(message: bytes) -> str:
    try:
        decoded_message = bytes(message).decode()
        if is_non_printable(decoded_message):
            return f"0x{hexlify(message).decode()}"
-       return decoded_message
+       else:
+           return decoded_message
    except UnicodeError:
        return f"0x{hexlify(message).decode()}"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

def decode_message(message: bytes) -> str:
    try:
        decoded_message = bytes(message).decode()
        if is_non_printable(decoded_message):
            return f"0x{hexlify(message).decode()}"
        else:
            return decoded_message
    except UnicodeError:
        return f"0x{hexlify(message).decode()}"
🧰 Tools
🪛 Ruff (0.8.2)

39-39: Consider moving this statement to an else block

(TRY300)

core/src/trezor/lvglui/scrs/template.py (2)

181-192: 🧹 Nitpick (assertive)

Added conditional warning banner for non-standard messages

The class now creates a warning banner when is_standard is False, using either the provided warning text or a default message. This improves user awareness of potentially risky operations.

Consider extracting the warning banner creation to a separate method for better readability:

- if not is_standard:
-     self.warning_banner = Banner(
-         self.content_area,
-         2,
-         warning_banner_text
-         or _(i18n_keys.CONTENT__NON_STANDARD_MESSAGE_SIGNATURE),
-     )
-     self.warning_banner.align_to(self.title, lv.ALIGN.OUT_BOTTOM_MID, 0, 40)
+ if not is_standard:
+     self._create_warning_banner(warning_banner_text)

With a helper method:

def _create_warning_banner(self, custom_text=None):
    self.warning_banner = Banner(
        self.content_area,
        2,
        custom_text or _(i18n_keys.CONTENT__NON_STANDARD_MESSAGE_SIGNATURE),
    )
    self.warning_banner.align_to(self.title, lv.ALIGN.OUT_BOTTOM_MID, 0, 40)

1090-1111: 🧹 Nitpick (assertive)

Added EIP712Warning class for Ethereum typed data warnings

New EIP712Warning class extends FullSizeWindow to display warnings for EIP712 typed data with appropriate formatting and content. This improves user safety when dealing with potentially risky structured data transactions.

Missing type annotations should be added to improve code quality:

def __init__(
    self, 
    title: str, 
-   warning_level, 
-   text, 
-   primary_type, 
-   primary_color, 
-   icon_path
+   warning_level: int,
+   text: str,
+   primary_type: str,
+   primary_color: int,
+   icon_path: str,
) -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

class EIP712Warning(FullSizeWindow):
    def __init__(
        self, 
        title: str, 
        warning_level: int,
        text: str,
        primary_type: str,
        primary_color: int,
        icon_path: str,
    ) -> None:
        super().__init__(
            title,
            None,
            _(i18n_keys.BUTTON__CONTINUE),
            _(i18n_keys.BUTTON__REJECT),
            anim_dir=2,
            primary_color=primary_color,
            icon_path=icon_path,
        )
        self.warning_banner = Banner(self.content_area, warning_level, text)
        self.warning_banner.align_to(self.title, lv.ALIGN.OUT_BOTTOM_MID, 0, 40)
        self.primary_type = DisplayItemNoBgc(
            self.content_area,
            "PrimaryType:",
            primary_type,
        )
        self.primary_type.align_to(self.warning_banner, lv.ALIGN.OUT_BOTTOM_LEFT, 0, 24)
🧰 Tools
🪛 Ruff (0.8.2)

1091-1091: Missing return type annotation for special method __init__

Add return type annotation: None

(ANN204)


1092-1092: Missing type annotation for function argument warning_level

(ANN001)


1092-1092: Missing type annotation for function argument text

(ANN001)


1092-1092: Missing type annotation for function argument primary_type

(ANN001)


1092-1092: Missing type annotation for function argument primary_color

(ANN001)


1092-1092: Missing type annotation for function argument icon_path

(ANN001)


1092-1092: Trailing comma missing

Add trailing comma

(COM812)

common/protob/messages-solana.proto (2)

79-82: 🧹 Nitpick (assertive)

Warning about message signing could be clearer.

The documentation comment describes this as for "arbitrary message except valid solana transaction" but could be more explicit about security risks.

/**
- * Request: ask device to sign arbitrary message except valid solana transaction
+ * Request: ask device to sign arbitrary message (WARNING: high security risk)
+ * This allows signing any data that is not a valid Solana transaction.
+ * USE WITH CAUTION: This bypasses all safety checks and can lead to loss of funds.
 * @start
 * @next SolanaMessageSignature
 * @next Failure
 */
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * Request: ask device to sign arbitrary message (WARNING: high security risk)
 * This allows signing any data that is not a valid Solana transaction.
 * USE WITH CAUTION: This bypasses all safety checks and can lead to loss of funds.
 * @start
 * @next SolanaMessageSignature
 * @next Failure
 */
message SolanaSignUnsafeMessage {
    repeated uint32 address_n = 1;          // BIP-32 path to derive the key from master node
    required bytes message = 2;             // the message to sign
}
🧰 Tools
🪛 Buf (1.47.2)

81-81: Field named %!q(MISSING) should not be required.

(FIELD_NOT_REQUIRED)


59-71: 💡 Verification agent

🧩 Analysis chain

Comprehensive off-chain message structure.

The SolanaSignOffChainMessage definition includes all necessary fields with good defaults and clear documentation.


🌐 Web query:

Are required fields in Protocol Buffers best practice or should they be optional?

💡 Result:

Protocol Buffers' required fields are strongly discouraged in practice despite their seemingly useful guarantee of data presence. Here's why and what to do instead:


Key Reasons to Avoid Required Fields

  1. Backward Compatibility Risks
    Once a field is marked required, removing or changing it breaks all existing clients/servers using that proto definition[1][3][6]. This creates maintenance nightmares in distributed systems where simultaneous upgrades are impossible.

  2. Forward Compatibility Issues
    New code using updated proto definitions can't safely interact with older systems if required fields are added later[4][7]. Versioned APIs become mandatory to prevent failures.

  3. Validation vs. Schema Enforcement
    Required fields attempt to enforce validation at the serialization layer, but real-world validation often needs context-specific rules (e.g., "email must contain @") that protobuf can't express[3][6]. Better to handle this in application logic.


Best Practices Instead of Required Fields

  1. Use Optional Fields + Application Validation

    message User {
      optional string email = 1;  // Proto3: no "optional" keyword needed
    }
    • Check field presence programmatically:
      if not user.email:
          raise ValidationError("Email required")
  2. Leverate Proto3's Default Behavior
    Proto3 treats all singular fields as optional by default, eliminating the required trap entirely[1][9].

  3. For Critical Fields, Use Documentation

    // (proto3 example)
    message Payment {
      string id = 1;           // System-generated, always present
      string currency_code = 2; // REQUIRED for processing
    }

    Combine clear comments with code checks for critical fields[8].


When Required Fields Cause Failures

Scenario Required Field Outcome Optional Field Alternative
Field removal All parsers fail[3][6] Old clients ignore new fields[9]
Partial upgrades Messages rejected[4] Systems degrade gracefully
Schema evolution Impossible without downtime Add new fields incrementally[2]

Migration Strategy for Existing Required Fields

  1. Convert to Optional

    • Proto2: Change requiredoptional
    • Proto3: Remove required (implicitly optional)[1]
  2. Reserve Field Numbers
    Prevent accidental reuse:

    reserved 4;          // Old required field ID
    reserved "username"; // Old field name
  3. Add Application Validation
    Implement equivalent checks in code while monitoring logs for missing data[7].


The Protocol Buffers team explicitly warns against required fields due to their long-term maintainability costs[2][6][8]. Modern practice favors optional fields with explicit validation, aligning with proto3's design philosophy of flexibility and safe schema evolution[1][9].

Citations:


Action Required: Update the message field declaration

The overall off-chain message structure is solid with good defaults and clear documentation. However, using a required field for message can lead to backward and forward compatibility issues. Protocol Buffers best practices now favor using optional fields along with application-level validation.

  • Location: common/protob/messages-solana.proto, lines 59-71
  • Recommendation: Change required bytes message = 2; to optional bytes message = 2; and add necessary validation in your application logic.
🧰 Tools
🪛 Buf (1.47.2)

67-67: Field named %!q(MISSING) should not be required.

(FIELD_NOT_REQUIRED)

core/src/apps/cardano/byron_addresses.py (2)

71-71: 🧹 Nitpick (assertive)

Error handling could be improved.

When raising exceptions in except blocks, use raise ... from err to preserve the error chain.

Example improvement for line 71:

-        raise ProcessError("Invalid address")
+        raise ProcessError("Invalid address") from e

For other error messages, consider creating standard error constants at the module level instead of repeating string literals.

Also applies to: 74-74, 78-78, 82-82, 85-85

🧰 Tools
🪛 Ruff (0.8.2)

71-71: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


71-71: Avoid specifying long messages outside the exception class

(TRY003)


54-60: 🧹 Nitpick (assertive)

Implementation of _address_hash could be improved.

The function can be simplified by removing the unnecessary res variable assignment.

def _address_hash(data: list) -> bytes:
    from trezor.crypto import hashlib

    cbor_data = cbor.encode(data)
    sha_data_hash = hashlib.sha3_256(cbor_data).digest()
-    res = hashlib.blake2b(data=sha_data_hash, outlen=28).digest()
-    return res
+    return hashlib.blake2b(data=sha_data_hash, outlen=28).digest()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

def _address_hash(data: list) -> bytes:
    from trezor.crypto import hashlib

    cbor_data = cbor.encode(data)
    sha_data_hash = hashlib.sha3_256(cbor_data).digest()
    return hashlib.blake2b(data=sha_data_hash, outlen=28).digest()
🧰 Tools
🪛 Ruff (0.8.2)

60-60: Unnecessary assignment to res before return statement

Remove unnecessary assignment

(RET504)

core/src/apps/common/keychain.py (1)

225-229: 🧹 Nitpick (assertive)

Better tuple handling for pattern variable.

The change ensures pattern is always treated as a tuple before being unpacked.

Add a trailing comma to line 228 for consistency:

-        *pattern, slip44_id=slip44_id, curve=curve, allow_testnet=allow_testnet
+        *pattern, slip44_id=slip44_id, curve=curve, allow_testnet=allow_testnet,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    pattern = pattern if isinstance(pattern, tuple) else (pattern,)
    return with_slip44_keychain(
        *pattern, slip44_id=slip44_id, curve=curve, allow_testnet=allow_testnet,
    )
🧰 Tools
🪛 Ruff (0.8.2)

228-228: Trailing comma missing

Add trailing comma

(COM812)

core/src/trezor/lvglui/scrs/homescreen.py (1)

901-908: 🧹 Nitpick (assertive)

Updated time format display logic.

The conditional flow now properly formats 0.5 minute settings in seconds format.

Two minor improvements:

-                if not item == "Never":  # last item
+                if item != "Never":  # last item
                     if item == 0.5:
                         item = _(i18n_keys.OPTION__STR_SECONDS).format(int(item * 60))
                     else:
                         item = _(
                             i18n_keys.ITEM__STATUS__STR_MINUTES
                             if item != 1
-                            else i18n_keys.OPTION__STR_MINUTE
+                            else i18n_keys.OPTION__STR_MINUTE,
                         ).format(item)

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

907-907: Trailing comma missing

Add trailing comma

(COM812)

python/src/trezorlib/cardano.py (7)

834-834: 🧹 Nitpick (assertive)

Boolean positional argument.
Consider making chunkify a keyword-only argument to follow style conventions.

🧰 Tools
🪛 Ruff (0.8.2)

834-834: Boolean-typed positional argument in function definition

(FBT001)


834-834: Boolean default positional argument in function definition

(FBT002)


853-853: 🧹 Nitpick (assertive)

Boolean positional argument.
Same recommendation for show_display.

🧰 Tools
🪛 Ruff (0.8.2)

853-853: Boolean-typed positional argument in function definition

(FBT001)


853-853: Boolean default positional argument in function definition

(FBT002)


903-903: 🧹 Nitpick (assertive)

Boolean positional argument.
Suggest making chunkify keyword-only here as well.

🧰 Tools
🪛 Ruff (0.8.2)

903-903: Boolean-typed positional argument in function definition

(FBT001)


903-903: Boolean default positional argument in function definition

(FBT002)


904-904: 🧹 Nitpick (assertive)

Boolean positional argument.
tag_cbor_sets would also benefit from being keyword-only.

🧰 Tools
🪛 Ruff (0.8.2)

904-904: Boolean-typed positional argument in function definition

(FBT001)


904-904: Boolean default positional argument in function definition

(FBT002)


423-443: 🧹 Nitpick (assertive)

Conway support with deposit field.
Good addition for STAKE_REGISTRATION_CONWAY and STAKE_DEREGISTRATION_CONWAY.
Include a trailing comma in line 431 to satisfy code style.

-            certificate, CERTIFICATE_MISSING_FIELDS_ERROR
+            certificate, CERTIFICATE_MISSING_FIELDS_ERROR,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    elif certificate_type in (
        messages.CardanoCertificateType.STAKE_REGISTRATION_CONWAY,
        messages.CardanoCertificateType.STAKE_DEREGISTRATION_CONWAY,
    ):
        if "deposit" not in certificate:
            raise CERTIFICATE_MISSING_FIELDS_ERROR

        path, script_hash, key_hash = _parse_credential(
            certificate, CERTIFICATE_MISSING_FIELDS_ERROR,
        )

        return (
            messages.CardanoTxCertificate(
                type=certificate_type,
                path=path,
                script_hash=script_hash,
                key_hash=key_hash,
                deposit=int(certificate["deposit"]),
            ),
            None,
        )
🧰 Tools
🪛 Ruff (0.8.2)

431-431: Trailing comma missing

Add trailing comma

(COM812)


489-512: 🧹 Nitpick (assertive)

Vote delegation certificate.
Well-structured approach for VOTE_DELEGATION.
Lines 494 and 507 missing trailing commas. Adding them improves consistency.

-        path, script_hash, key_hash = _parse_credential(
+        path, script_hash, key_hash = _parse_credential(,

-                    certificate["drep"].get("script_hash")
+                    certificate["drep"].get("script_hash"),

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

494-494: Trailing comma missing

Add trailing comma

(COM812)


507-507: Trailing comma missing

Add trailing comma

(COM812)


610-651: 🧹 Nitpick (assertive)

CVote registration parameters.
This CIP36-related code looks good.
Consider adding trailing commas on lines 626 and 635.

-        weight=int(delegation["weight"])
+        weight=int(delegation["weight"]),


-            vote_public_key=parse_optional_bytes(
+            vote_public_key=parse_optional_bytes(

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

626-626: Trailing comma missing

Add trailing comma

(COM812)


635-635: Trailing comma missing

Add trailing comma

(COM812)

core/src/trezor/enums/SolanaOffChainMessageFormat.py (1)

5-6: 🧹 Nitpick (assertive)

Add brief documentation for clarity.

Adding a short comment explaining what these formats represent would help other developers understand their purpose.

+# V0_RESTRICTED_ASCII: Format supporting only ASCII characters
 V0_RESTRICTED_ASCII = 0
+# V0_LIMITED_UTF8: Format supporting a subset of UTF-8 characters
 V0_LIMITED_UTF8 = 1
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

# V0_RESTRICTED_ASCII: Format supporting only ASCII characters
V0_RESTRICTED_ASCII = 0
# V0_LIMITED_UTF8: Format supporting a subset of UTF-8 characters
V0_LIMITED_UTF8 = 1
core/src/apps/ethereum/sign_message.py (1)

41-41: 🧹 Nitpick (assertive)

Consistent use of non-strict key derivation

The change mirrors modification in other Ethereum functions. Ensure non-strict derivation is appropriate for message signing context.

Consider documenting the security impact of this change and situations where non-standard paths are necessary for compatibility.

core/src/apps/ethereum/onekey/get_public_key.py (1)

24-24: 🧹 Nitpick (assertive)

Key derivation uses consistent non-strict approach

Relaxed key derivation allows for more flexible paths. Ensure this approach has been security reviewed.

This appears to be a systematic change across the Ethereum code. Document the rationale for this relaxation in relevant design documentation.

core/src/apps/ethereum/get_address.py (2)

24-24: 🧹 Nitpick (assertive)

Consider documenting the purpose of non-strict path validation.

Adding force_strict=False relaxes path validation. This might be intentional for compatibility but lacks explanatory comments.

-    await paths.validate_path(ctx, keychain, msg.address_n, force_strict=False)
+    # Non-strict validation allows custom derivation paths beyond standard BIP-44
+    await paths.validate_path(ctx, keychain, msg.address_n, force_strict=False)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    # Non-strict validation allows custom derivation paths beyond standard BIP-44
    await paths.validate_path(ctx, keychain, msg.address_n, force_strict=False)

26-26: 🧹 Nitpick (assertive)

Same recommendation for key derivation.

Similar to the previous comment, the relaxed path derivation needs documentation.

-    node = keychain.derive(msg.address_n, force_strict=False)
+    # Allow deriving keys from non-standard paths for advanced use cases
+    node = keychain.derive(msg.address_n, force_strict=False)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    # Allow deriving keys from non-standard paths for advanced use cases
    node = keychain.derive(msg.address_n, force_strict=False)
core/src/apps/ethereum/onekey/sign_message.py (1)

28-28: 🧹 Nitpick (assertive)

New parameter adds flexibility for path validation

The force_strict=False parameter relaxes path validation rules, useful when supporting non-standard derivation paths.

Consider adding a code comment explaining when non-strict validation is appropriate for better maintainability.

core/src/apps/cardano/sign_message.py (1)

39-41: 🧹 Nitpick (assertive)

Use named parameter instead of positional boolean

The boolean parameter True lacks clarity on its purpose.

-        True,
+        force_strict=True,

This makes the code more self-documenting and aligns with the style used in other modules.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        force_strict=True,
        # path must match the PUBKEY schema
        (SCHEMA_PUBKEY.match(msg.address_n) or SCHEMA_MINT.match(msg.address_n)),
🧰 Tools
🪛 Ruff (0.8.2)

39-39: Boolean positional value in function call

(FBT003)

core/src/apps/ethereum/onekey/sign_typed_data_hash.py (1)

25-26: 🧹 Nitpick (assertive)

Consider documenting non-strict path behavior

The function signature doesn't reflect the relaxed path behavior. Add a docstring or update parameter list to document this important security choice.

🧰 Tools
🪛 Ruff (0.8.2)

25-25: Trailing comma missing

Add trailing comma

(COM812)

python/src/trezorlib/messages.py (1)

2053-2082: 🧹 Nitpick (assertive)

PSBT signing message classes well implemented.

New classes SignPsbt and SignedPsbt follow protocol buffer patterns consistently with the rest of the codebase.

Note: The static analyzer suggests using typing.ClassVar for mutable class attributes, but this matches existing code style.

🧰 Tools
🪛 Ruff (0.8.2)

2055-2058: Mutable class attributes should be annotated with typing.ClassVar

(RUF012)


2072-2074: Mutable class attributes should be annotated with typing.ClassVar

(RUF012)

core/src/apps/cardano/sign_tx/pool_owner_signer.py (4)

64-67: 🧹 Nitpick (assertive)

Unused parameter in _should_show_output method

The output parameter is declared but never used in the method body.

-def _should_show_output(self, output: messages.CardanoTxOutput) -> bool:
+def _should_show_output(self, _output: messages.CardanoTxOutput) -> bool:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def _should_show_output(self, _output: messages.CardanoTxOutput) -> bool:
        # super() omitted intentionally
        # There are no spending witnesses, it is thus safe to hide outputs.
        return False
🧰 Tools
🪛 Ruff (0.8.2)

64-64: Unused method argument: output

(ARG002)


74-74: 🧹 Nitpick (assertive)

Error message should be in exception class

Move the error message to the exception constructor.

-            raise ProcessError("Invalid certificate")
+            raise ProcessError("Invalid certificate")

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

74-74: Avoid specifying long messages outside the exception class

(TRY003)


62-62: 🧹 Nitpick (assertive)

Error message should be in exception class

Move the error message to the exception constructor.

-            raise ProcessError("Invalid output")
+            raise ProcessError("Invalid output")

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

62-62: Avoid specifying long messages outside the exception class

(TRY003)


76-88: 🧹 Nitpick (assertive)

Enhanced witness request validation

Added validation check ensures that the witness request path matches the pool owner path. Add missing trailing comma after parameters.

def _validate_witness_request(
-        self, witness_request: messages.CardanoTxWitnessRequest
+        self, witness_request: messages.CardanoTxWitnessRequest,
    ) -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def _validate_witness_request(
        self, witness_request: messages.CardanoTxWitnessRequest,
    ) -> None:
        from ..helpers.paths import SCHEMA_STAKING_ANY_ACCOUNT

        super()._validate_witness_request(witness_request)
        if not (
            SCHEMA_STAKING_ANY_ACCOUNT.match(witness_request.path)
            and witness_request.path == self.pool_owner_path
        ):
            raise ProcessError(
                "Stakepool registration transaction can only contain the pool owner witness request"
            )
🧰 Tools
🪛 Ruff (0.8.2)

77-77: Trailing comma missing

Add trailing comma

(COM812)


86-88: Avoid specifying long messages outside the exception class

(TRY003)


87-87: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/cardano/get_native_script_hash.py (1)

13-15: 🧹 Nitpick (assertive)

Function signature type changes

Updated parameter and return types to use direct class references. Add missing trailing comma.

async def get_native_script_hash(
-    ctx: wire.Context, msg: CardanoGetNativeScriptHash, keychain: seed.Keychain
+    ctx: wire.Context, msg: CardanoGetNativeScriptHash, keychain: seed.Keychain,
) -> CardanoNativeScriptHash:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

async def get_native_script_hash(
    ctx: wire.Context, msg: CardanoGetNativeScriptHash, keychain: seed.Keychain,
) -> CardanoNativeScriptHash:
🧰 Tools
🪛 Ruff (0.8.2)

14-14: Trailing comma missing

Add trailing comma

(COM812)

common/protob/messages.proto (2)

159-160: 🧹 Nitpick (assertive)

New Bitcoin PSBT message types look good

Added support for Bitcoin PSBT signing with MessageType_SignPsbt and MessageType_SignedPsbt.

Style guide suggests UPPER_SNAKE_CASE for enum values (MESSAGE_TYPE_SIGN_PSBT), but these follow the existing pattern in the file.

🧰 Tools
🪛 Buf (1.47.2)

159-159: Enum value name "MessageType_SignPsbt" should be UPPER_SNAKE_CASE, such as "MESSAGE_TYPE_SIGN_PSBT".

(ENUM_VALUE_UPPER_SNAKE_CASE)


160-160: Enum value name "MessageType_SignedPsbt" should be UPPER_SNAKE_CASE, such as "MESSAGE_TYPE_SIGNED_PSBT".

(ENUM_VALUE_UPPER_SNAKE_CASE)


460-462: 🧹 Nitpick (assertive)

New Solana message types enhance functionality

Added three new message types for Solana operations: off-chain message signing, message signatures, and unsafe message signing.

Same naming convention note applies here - follows existing pattern rather than UPPER_SNAKE_CASE.

🧰 Tools
🪛 Buf (1.47.2)

460-460: Enum value name "MessageType_SolanaSignOffChainMessage" should be UPPER_SNAKE_CASE, such as "MESSAGE_TYPE_SOLANA_SIGN_OFF_CHAIN_MESSAGE".

(ENUM_VALUE_UPPER_SNAKE_CASE)


461-461: Enum value name "MessageType_SolanaMessageSignature" should be UPPER_SNAKE_CASE, such as "MESSAGE_TYPE_SOLANA_MESSAGE_SIGNATURE".

(ENUM_VALUE_UPPER_SNAKE_CASE)


462-462: Enum value name "MessageType_SolanaSignUnsafeMessage" should be UPPER_SNAKE_CASE, such as "MESSAGE_TYPE_SOLANA_SIGN_UNSAFE_MESSAGE".

(ENUM_VALUE_UPPER_SNAKE_CASE)

core/src/trezor/lvglui/i18n/locales/zh_cn.py (6)

690-690: 🧹 Nitpick (assertive)

Error message wording improved

Message now states PIN errors "reached" 10 times rather than "exceeded" 10 times. More accurate description.

Replace full-width comma (,) with standard comma (,) for consistency.

🧰 Tools
🪛 Ruff (0.8.2)

690-690: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


746-747: 🧹 Nitpick (assertive)

Simplified network terminology

Updated "ETH 和 EVM 兼容链" to "ETH 和 EVM 网络" - focuses on networks rather than chain compatibility.

Replace full-width comma (,) with standard comma (,) in line 747.

🧰 Tools
🪛 Ruff (0.8.2)

747-747: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


750-750: 🧹 Nitpick (assertive)

Higher battery warning threshold

Battery warning threshold changed from <10% to <20%, giving users earlier notification to charge.

Replace full-width parentheses and commas with standard ASCII versions.

🧰 Tools
🪛 Ruff (0.8.2)

750-750: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


750-750: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


750-750: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


750-750: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


750-750: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


756-757: 🧹 Nitpick (assertive)

Improved desktop app download instructions

Added a space between "OneKey" and "App" for better readability in the desktop download instructions.

Replace full-width colon (:) with standard colon (:).

🧰 Tools
🪛 Ruff (0.8.2)

756-756: String contains ambiguous (FULLWIDTH COLON). Did you mean : (COLON)?

(RUF001)


803-824: 🧹 Nitpick (assertive)

New user-facing messages for wallet functionality

Added important translations for wallet compatibility messages, error states, and network selection.

Several lines contain full-width punctuation characters that should be replaced with standard ASCII ones for consistency.

🧰 Tools
🪛 Ruff (0.8.2)

804-804: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


805-805: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


807-807: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


810-810: String contains ambiguous (FULLWIDTH COLON). Did you mean : (COLON)?

(RUF001)


811-811: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


811-811: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


813-813: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


813-813: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


813-813: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


823-823: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


823-823: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


825-876: 🧹 Nitpick (assertive)

Added FIDO key management translations

Comprehensive translations for FIDO security key functionality, including registration flow, management, and authentication.

Several full-width punctuation marks should be replaced with standard ASCII versions.

🧰 Tools
🪛 Ruff (0.8.2)

826-826: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


828-828: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


828-828: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


840-840: String contains ambiguous (FULLWIDTH QUESTION MARK). Did you mean ? (QUESTION MARK)?

(RUF001)


850-850: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


850-850: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


852-852: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


852-852: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


867-867: String contains ambiguous (FULLWIDTH QUESTION MARK). Did you mean ? (QUESTION MARK)?

(RUF001)

core/src/apps/cardano/helpers/bech32.py (1)

38-41: 🧹 Nitpick (assertive)

Simplified error handling logic

Error check is now at the beginning of the function. This makes the code more readable by reducing nesting.

Consider using a named parameter for the boolean argument in convertbits:

-decoded = bech32.convertbits(data, 5, 8, False)
+decoded = bech32.convertbits(data, 5, 8, pad=False)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if data is None:
        raise ValueError
    decoded = bech32.convertbits(data, 5, 8, pad=False)
    return bytes(decoded)
🧰 Tools
🪛 Ruff (0.8.2)

40-40: Boolean positional value in function call

(FBT003)

core/src/apps/cardano/helpers/hash_builder_collection.py (1)

26-26: 🧹 Nitpick (assertive)

Remove quotes from type annotation

Static analysis suggests removing quotes from the type hint.

-        self.parent: "HashBuilderCollection | None" = None
+        self.parent: HashBuilderCollection | None = None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        self.parent: HashBuilderCollection | None = None
🧰 Tools
🪛 Ruff (0.8.2)

26-26: Remove quotes from type annotation

Remove quotes

(UP037)

python/src/trezorlib/solana.py (2)

32-49: 🧹 Nitpick (assertive)

New Solana off-chain message signing function

Adds support for signing off-chain Solana messages with version, format control, and optional domain parameters.

Add return type annotation for clarity:

@expect(messages.SolanaMessageSignature)
def sign_offchain_message(
    client: "TrezorClient",
    n: "Address",
    message: bytes,
    message_version: messages.SolanaOffChainMessageVersion,
    message_format: messages.SolanaOffChainMessageFormat,
-    application_domain: Optional[str] = None
+    application_domain: Optional[str] = None,
-):
+) -> messages.SolanaMessageSignature:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

@expect(messages.SolanaMessageSignature)
def sign_offchain_message(
    client: "TrezorClient",
    n: "Address",
    message: bytes,
    message_version: messages.SolanaOffChainMessageVersion,
    message_format: messages.SolanaOffChainMessageFormat,
    application_domain: Optional[str] = None,
) -> messages.SolanaMessageSignature:
    msg = messages.SolanaSignOffChainMessage(
        message=message,
        address_n=n,
        message_version=message_version,
        message_format=message_format,
        application_domain=bytes.fromhex(application_domain) if application_domain else None,
    )
    return client.call(msg)
🧰 Tools
🪛 Ruff (0.8.2)

33-33: Missing return type annotation for public function sign_offchain_message

(ANN201)


39-39: Trailing comma missing

Add trailing comma

(COM812)


51-60: 🧹 Nitpick (assertive)

Unsafe message signing support

Implements a simplified signing function for unsafe messages.

Add return type annotation for consistency:

@expect(messages.SolanaMessageSignature)
def sign_unsafe_message(
    client: "TrezorClient",
    n: "Address",
    message: bytes,
-):
+) -> messages.SolanaMessageSignature:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

@expect(messages.SolanaMessageSignature)
def sign_unsafe_message(
    client: "TrezorClient",
    n: "Address",
    message: bytes,
) -> messages.SolanaMessageSignature:
    msg = messages.SolanaSignUnsafeMessage(
        message=message,
        address_n=n,
    )
    return client.call(msg)
🧰 Tools
🪛 Ruff (0.8.2)

51-51: Missing return type annotation for public function sign_unsafe_message

(ANN201)

python/src/trezorlib/cli/sol.py (2)

86-93: 🧹 Nitpick (assertive)

Clear branching between safe and unsafe signing

Good conditional logic for selecting appropriate signing method with proper parameter passing.

Consider refactoring the public_key return value for consistency:

    return {
-        "public_key": f"0x{rep.public_key.hex()}" if not unsafe else None,
+        "public_key": f"0x{rep.public_key.hex()}" if hasattr(rep, "public_key") and rep.public_key else None,
        "signature": f"0x{rep.signature.hex()}",
    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if unsafe:
        rep = solana.sign_unsafe_message(client, address_n, tools.prepare_message_bytes(message))
    else:
        rep = solana.sign_offchain_message(client, address_n, tools.prepare_message_bytes(message), message_version, message_format, application_domain)
    return {
        "public_key": f"0x{rep.public_key.hex()}" if hasattr(rep, "public_key") and rep.public_key else None,
        "signature": f"0x{rep.signature.hex()}",
    }

68-93: 🧹 Nitpick (assertive)

Comprehensive Solana message signing CLI command

Adds CLI support for both safe and unsafe Solana message signing with appropriate parameters and options.

Add return type annotation and fix missing trailing comma:

def sign_message(client: "TrezorClient",
    address: str,
    message: str,
    message_version: str,
    message_format: str,
    application_domain: Optional[str],
-    unsafe: bool
+    unsafe: bool,
+) -> dict[str, str]:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

@cli.command()
@click.option("-n", "--address", required=True, help=PATH_HELP)
@click.option("-v", "--message-version", type=ChoiceType(MESSAGE_VERSIONS), default="v0")
@click.option("-f", "--message-format", type=ChoiceType(MESSAGE_FORMATS), default="ascii")
@click.option("-d", "--application-domain", default=None, help="32 bytes hex encoded application domain or None")
@click.option("-u", "--unsafe", is_flag=True, help="Use unsafe message signing protocol")
@click.argument("message")
@with_client
def sign_message(client: "TrezorClient",
    address: str,
    message: str,
    message_version: str,
    message_format: str,
    application_domain: Optional[str],
    unsafe: bool,
) -> dict[str, str]:
    """Sign Solana message."""
    address_n = tools.parse_path(address)
    if unsafe:
        rep = solana.sign_unsafe_message(client, address_n, tools.prepare_message_bytes(message))
    else:
        rep = solana.sign_offchain_message(client, address_n, tools.prepare_message_bytes(message), message_version, message_format, application_domain)
    return {
        "public_key": f"0x{rep.public_key.hex()}" if not unsafe else None,
        "signature": f"0x{rep.signature.hex()}",
    }
🧰 Tools
🪛 Ruff (0.8.2)

76-76: Missing return type annotation for public function sign_message

(ANN201)


82-82: Boolean-typed positional argument in function definition

(FBT001)


82-82: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/cardano/native_script.py (5)

123-129: 🧹 Nitpick (assertive)

Improve imports organization.

Moving imports closer to where they're used can help with faster module loading, but consider grouping top-level imports for better maintainability.


143-175: 🧹 Nitpick (assertive)

Use named tuples for improved readability in complex conditionals.

The multiple conditionals checking different script types could benefit from using named constants or enums for the different groups of types.

🧰 Tools
🪛 Ruff (0.8.2)

149-149: Avoid specifying long messages outside the exception class

(TRY003)


150-163: Combine if branches using logical or operator

Combine if branches

(SIM114)


43-55: 🧹 Nitpick (assertive)

Consider consolidating similar conditional blocks.

The if-elif blocks for CNST.ALL and CNST.ANY have identical bodies. Consider combining them to reduce duplication.

-    elif script_type == CNST.ALL:
-        for sub_script in scripts:
-            validate_native_script(sub_script)
-    elif script_type == CNST.ANY:
-        for sub_script in scripts:
-            validate_native_script(sub_script)
+    elif script_type in (CNST.ALL, CNST.ANY):
+        for sub_script in scripts:
+            validate_native_script(sub_script)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    elif script_type in (CNST.ALL, CNST.ANY):
        for sub_script in scripts:
            validate_native_script(sub_script)
    elif script_type == CNST.N_OF_K:
        if script.required_signatures_count is None:
            raise INVALID_NATIVE_SCRIPT
        if script.required_signatures_count > len(scripts):
            raise INVALID_NATIVE_SCRIPT
        for sub_script in scripts:
            validate_native_script(sub_script)
🧰 Tools
🪛 Ruff (0.8.2)

43-48: Combine if branches using logical or operator

Combine if branches

(SIM114)


117-117: 🧹 Nitpick (assertive)

Improve exception message specificity.

Generic error messages make debugging harder. Consider specifying what makes the script invalid.

-        raise ProcessError("Invalid native script")
+        raise ProcessError("Invalid native script: unsupported structure")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        raise ProcessError("Invalid native script: unsupported structure")
🧰 Tools
🪛 Ruff (0.8.2)

117-117: Avoid specifying long messages outside the exception class

(TRY003)


179-179: 🧹 Nitpick (assertive)

Consider using tuple unpacking for cleaner code.

The function could use tuple unpacking instead of concatenation as suggested by the static analysis.

-    return (script_type,) + script_content
+    return (script_type, *script_content)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    return (script_type, *script_content)
🧰 Tools
🪛 Ruff (0.8.2)

179-179: Consider (script_type, *script_content) instead of concatenation

Replace with (script_type, *script_content)

(RUF005)

python/src/trezorlib/ton.py (2)

1-1: 🧹 Nitpick (assertive)

Use built-in list instead of typing.List.

List from the typing module is deprecated in modern Python versions. Switching to the built-in list type helps avoid deprecation warnings and improves forward compatibility.

-from typing import TYPE_CHECKING, List, Optional
+from typing import TYPE_CHECKING, Optional
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

from typing import TYPE_CHECKING, Optional
🧰 Tools
🪛 Ruff (0.8.2)

1-1: typing.List is deprecated, use list instead

(UP035)


52-55: 🧹 Nitpick (assertive)

Unify type hints and add a trailing comma.

Use the built-in list hints for these optional parameters, and consider adding a trailing comma on the last parameter for cleaner diffs.

-                ext_destination: Optional[List[str]] = None,
-                ext_ton_amount: Optional[List[int]] = None,
-                ext_payload: Optional[List[str]] = None,
-                signing_message_hash: Optional[str] = None
+                ext_destination: Optional[list[str]] = None,
+                ext_ton_amount: Optional[list[int]] = None,
+                ext_payload: Optional[list[str]] = None,
+                signing_message_hash: Optional[str] = None,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                ext_destination: Optional[list[str]] = None,
                ext_ton_amount: Optional[list[int]] = None,
                ext_payload: Optional[list[str]] = None,
                signing_message_hash: Optional[str] = None,
🧰 Tools
🪛 Ruff (0.8.2)

52-52: Use list instead of List for type annotation

Replace with list

(UP006)


53-53: Use list instead of List for type annotation

Replace with list

(UP006)


54-54: Use list instead of List for type annotation

Replace with list

(UP006)


55-55: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/bitcoin/sign_message.py (1)

64-65: 🧹 Nitpick (assertive)

Consider adding trailing commas for multiline calls.

Improve code readability in lines 64-65, 68-70, and 72 by adding trailing commas in multiline function calls. This helps keep diffs clean.

-            sighash = sighash_bip143(
-                message, script_pub, pubkey_hash, coin.sign_hash_double
-            )
+            sighash = sighash_bip143(
+                message,
+                script_pub,
+                pubkey_hash,
+                coin.sign_hash_double,
+            )

-            witness = utils.empty_bytearray(
-                1 + 1 + len(signature) + 1 + len(node.public_key()) + 1
-            )
+            witness = utils.empty_bytearray(
+                1 + 1 + len(signature) + 1 + len(node.public_key()) + 1,
+            )

-            write_witness_p2wpkh(
-                witness, signature, node.public_key(), SigHashType.SIGHASH_ALL
-            )
+            write_witness_p2wpkh(
+                witness,
+                signature,
+                node.public_key(),
+                SigHashType.SIGHASH_ALL,
+            )

Also applies to: 68-70, 72-72

🧰 Tools
🪛 Ruff (0.8.2)

65-65: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/cardano/sign_tx/plutus_signer.py (1)

88-94: 🧹 Nitpick (assertive)

Add trailing comma and consider extracting error message

The error message could be improved by storing it in a constant or providing more detail.

-            raise wire.ProcessError("Invalid certificate")
+            raise wire.ProcessError("Invalid certificate: stake pool registration not allowed in Plutus transactions")

Also, add a trailing comma after the parameter:

-    def _validate_witness_request(self, witness_request: messages.CardanoTxWitnessRequest) -> None:
+    def _validate_witness_request(self, witness_request: messages.CardanoTxWitnessRequest,) -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def _validate_certificate(self, certificate: messages.CardanoTxCertificate) -> None:
        from trezor.enums import CardanoCertificateType

        super()._validate_certificate(certificate)
        if certificate.type == CardanoCertificateType.STAKE_POOL_REGISTRATION:
            raise wire.ProcessError("Invalid certificate: stake pool registration not allowed in Plutus transactions")

    def _validate_witness_request(self, witness_request: messages.CardanoTxWitnessRequest,) -> None:
        # Original implementation goes here.
        pass
🧰 Tools
🪛 Ruff (0.8.2)

93-93: Avoid specifying long messages outside the exception class

(TRY003)

core/src/apps/bitcoin/sign_taproot.py (4)

34-36: 🧹 Nitpick (assertive)

Reduce function complexity.

This function is too big and hard to maintain. Consider breaking it into smaller helpers.

🧰 Tools
🪛 Ruff (0.8.2)

34-34: sign_taproot is too complex (33 > 10)

(C901)


35-35: Trailing comma missing

Add trailing comma

(COM812)


42-47: 🧹 Nitpick (assertive)

Avoid catching broad Exception.

Catching Exception can hide problems. Catch specific exceptions, or re-raise with raise wire.DataError(...) from e to keep the original traceback.

🧰 Tools
🪛 Ruff (0.8.2)

42-42: Do not catch blind exception: Exception

(BLE001)


47-47: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


47-47: Avoid specifying long messages outside the exception class

(TRY003)


73-73: 🛠️ Refactor suggestion

Replace runtime asserts with proper error handling.

Using assert in production code can hide real issues when __debug__ is False. Raise a custom error or wire.DataError for clarity.

Also applies to: 84-84, 86-86, 89-89, 224-224

🧰 Tools
🪛 Ruff (0.8.2)

73-73: Use of assert detected

(S101)


73-73: Assertion should be broken down into multiple parts

(PT018)


88-89: 🧹 Nitpick (assertive)

Use next(iter(...)) instead of slicing the first item from a dict.

Slicing can be slower and less clear. For example:

- script, _ = list(input.tap_scripts.keys())[0]
+ script, _ = next(iter(input.tap_scripts.keys()))

Also applies to: 200-201

🧰 Tools
🪛 Ruff (0.8.2)

88-88: Prefer next(iter(input.tap_scripts.keys())) over single element slice

Replace with next(iter(input.tap_scripts.keys()))

(RUF015)


89-89: Use of assert detected

(S101)

core/src/apps/ethereum/onekey/sign_tx_eip1559.py (1)

109-109: 🧹 Nitpick (assertive)

Reassess force_strict=False on derivation.

Loosening path checks might allow unintended derivations. Ensure there's a good reason to skip strict mode.

Also applies to: 201-201

core/src/apps/cardano/get_address.py (3)

37-37: 🧹 Nitpick (assertive)

Add a trailing comma in the function call.

This prevents merge conflicts and is more readable in diffs.

🧰 Tools
🪛 Ruff (0.8.2)

37-37: Trailing comma missing

Add trailing comma

(COM812)


42-42: 🧹 Nitpick (assertive)

Raise exceptions with a cause.

Use raise wire.ProcessError("Deriving address failed") from e to maintain original context.

🧰 Tools
🪛 Ruff (0.8.2)

42-42: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


42-42: Avoid specifying long messages outside the exception class

(TRY003)


17-18: 🧹 Nitpick (assertive)

Add a trailing comma in the function signature.

It’s more consistent. Example:

- async def get_address(ctx: wire.Context, msg: CardanoGetAddress, keychain: seed.Keychain)
+ async def get_address(
+     ctx: wire.Context,
+     msg: CardanoGetAddress,
+     keychain: seed.Keychain,
+ )

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

17-17: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/bitcoin/psbt/key.py (2)

55-55: 🛠️ Refactor suggestion

Use a dedicated exception class and keep the message concise.

Instead of raising a raw Exception, introduce a custom exception for better clarity:

+class InvalidExtendedKeyError(Exception):
+    pass

 def from_bytes(cls, data: bytes) -> "ExtendedPubKey":
     version = data[0:4]
     if version not in [
         ExtendedPubKey.MAINNET_PUBLIC,
         ExtendedPubKey.TESTNET_PUBLIC,
     ]:
-        raise Exception(f"Extended key magic of {version.hex()} is invalid")
+        raise InvalidExtendedKeyError(f"Bad magic: {version.hex()}")
     depth = data[4]
     ...
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

class InvalidExtendedKeyError(Exception):
    pass

def from_bytes(cls, data: bytes) -> "ExtendedPubKey":
    version = data[0:4]
    if version not in [
        ExtendedPubKey.MAINNET_PUBLIC,
        ExtendedPubKey.TESTNET_PUBLIC,
    ]:
        raise InvalidExtendedKeyError(f"Bad magic: {version.hex()}")
    depth = data[4]
    ...
🧰 Tools
🪛 Ruff (0.8.2)

55-55: Create your own exception

(TRY002)


55-55: Avoid specifying long messages outside the exception class

(TRY003)


185-186: ⚠️ Potential issue

Avoid catching a blind exception and chain the original error.

Catching Exception can mask unexpected issues. Use a narrower exception or chain the original:

-    except Exception:
-        raise ValueError("Invalid BIP32 path", nstr)
+    except (ValueError, TypeError) as exc:
+        raise ValueError("Invalid BIP32 path", nstr) from exc
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    except (ValueError, TypeError) as exc:
        raise ValueError("Invalid BIP32 path", nstr) from exc
🧰 Tools
🪛 Ruff (0.8.2)

185-185: Do not catch blind exception: Exception

(BLE001)


186-186: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


186-186: Avoid specifying long messages outside the exception class

(TRY003)

core/src/apps/solana/sign_unsafe_message.py (3)

53-53: ⚠️ Potential issue

Avoid catching BaseException.

Use Exception or a more specific subclass to avoid catching system exits and keyboard interrupts.

-    except BaseException as e:
+    except Exception as e:
     if __debug__:
         ...
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    except Exception as e:
     if __debug__:
         ...
🧰 Tools
🪛 Ruff (0.8.2)

53-53: Do not catch blind exception: BaseException

(BLE001)


52-52: 🧹 Nitpick (assertive)

Create a specialized error instead of using a plain wire.DataError.

A custom error type clarifies the context. Keep the message short.

-        raise wire.DataError("Valid transaction message format is not allowed")
+        raise wire.DataError("Disallowed message format")

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

52-52: Abstract raise to an inner function

(TRY301)


52-52: Avoid specifying long messages outside the exception class

(TRY003)


25-25: 🧹 Nitpick (assertive)

Add a trailing comma in the function signature for consistency.

This is a minor style improvement and helps maintain a consistent code format.

 async def sign_unsafe_message(
     ctx: wire.Context, msg: SolanaSignUnsafeMessage, keychain: Keychain
-) -> SolanaMessageSignature:
+) -> SolanaMessageSignature:

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

25-25: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/cardano/sign_tx/__init__.py (2)

30-30: 🧹 Nitpick (assertive)

Update deprecated Type usage

Type from typing is deprecated. Use Python's built-in type instead.

-signer_type: Type[Signer]
+signer_type: type[Signer]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    signer_type: type[Signer]
🧰 Tools
🪛 Ruff (0.8.2)

30-30: Use type instead of Type for type annotation

Replace with type

(UP006)


16-18: 🧹 Nitpick (assertive)

Fix type annotation and add trailing comma

The function signature updates the parameter and return types but is missing a trailing comma after the parameter list.

async def sign_tx(
-    ctx: wire.Context, msg: CardanoSignTxInit, keychain: seed.Keychain
+    ctx: wire.Context, msg: CardanoSignTxInit, keychain: seed.Keychain,
) -> CardanoSignTxFinished:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

async def sign_tx(
    ctx: wire.Context, msg: CardanoSignTxInit, keychain: seed.Keychain,
) -> CardanoSignTxFinished:
🧰 Tools
🪛 Ruff (0.8.2)

17-17: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/cardano/helpers/account_path_check.py (2)

60-61: 🧹 Nitpick (assertive)

Add missing trailing comma

Add a trailing comma after function parameters to maintain consistent code style.

is_control_path_byron_or_shelley = seed.is_byron_path(
-            self_account_path
+            self_account_path,
) or seed.is_shelley_path(self_account_path)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

is_control_path_byron_or_shelley = seed.is_byron_path(
            self_account_path,
) or seed.is_shelley_path(self_account_path)
🧰 Tools
🪛 Ruff (0.8.2)

60-60: Trailing comma missing

Add trailing comma

(COM812)


58-58: 🧹 Nitpick (assertive)

Replace assert with explicit error handling

Using assert in production code is risky as assertions can be disabled with the -O flag. Consider using explicit error handling instead.

-assert isinstance(self_account_path, list)
+if not isinstance(self_account_path, list):
+    raise ProcessError("Invalid account path")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        if not isinstance(self_account_path, list):
            raise ProcessError("Invalid account path")
🧰 Tools
🪛 Ruff (0.8.2)

58-58: Use of assert detected

(S101)

core/src/apps/solana/sign_offchain_message.py (2)

107-107: 🧹 Nitpick (assertive)

Add a return type annotation.

Mark sanitize_message as returning None for clarity:

-def sanitize_message(msg: SolanaSignOffChainMessage):
+def sanitize_message(msg: SolanaSignOffChainMessage) -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

def sanitize_message(msg: SolanaSignOffChainMessage) -> None:
🧰 Tools
🪛 Ruff (0.8.2)

107-107: Missing return type annotation for public function sanitize_message

Add return type annotation: None

(ANN201)


133-136: 🧹 Nitpick (assertive)

Optional exception chaining.

If you want to preserve the original error message, capture the exception as e and raise from it.

-except UnicodeDecodeError:
-    raise wire.DataError("Message format 1 must be a valid UTF-8 string")
+except UnicodeDecodeError as e:
+    raise wire.DataError("Message format 1 must be a valid UTF-8 string") from e
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        try:
            message.decode("utf-8")
        except UnicodeDecodeError as e:
            raise wire.DataError("Message format 1 must be a valid UTF-8 string") from e
🧰 Tools
🪛 Ruff (0.8.2)

136-136: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


136-136: Avoid specifying long messages outside the exception class

(TRY003)

core/src/apps/cardano/get_public_key.py (3)

18-18: 🧹 Nitpick (assertive)

Add trailing comma for consistency.

Consider adding a trailing comma at the end of the parameter list to align with Python style.

🧰 Tools
🪛 Ruff (0.8.2)

18-18: Trailing comma missing

Add trailing comma

(COM812)


33-33: 🧹 Nitpick (assertive)

Use named argument for better clarity.

Passing True as a positional argument can be cryptic. Switch to a named argument.

🧰 Tools
🪛 Ruff (0.8.2)

33-33: Boolean positional value in function call

(FBT003)


58-58: 🧹 Nitpick (assertive)

Add trailing comma for consistency.

A trailing comma may improve diffs if parameters change later.

🧰 Tools
🪛 Ruff (0.8.2)

58-58: Trailing comma missing

Add trailing comma

(COM812)

python/src/trezorlib/cli/ton.py (7)

61-61: 🧹 Nitpick (assertive)

Prefer built-in typing for return types.
Returning Dict[str, str] is fine, but consider dict[str, str] when Python 3.9+ is available. Reduces clutter.

🧰 Tools
🪛 Ruff (0.8.2)

61-61: Use dict instead of Dict for type annotation

Replace with dict

(UP006)


112-114: 🧹 Nitpick (assertive)

Use built-in tuple types.
Replace Tuple[...] with tuple[...] to match current Python typing practices.

-                ext_destination: Tuple[str, ...],
-                ext_ton_amount: Tuple[int, ...],
-                ext_payload: Tuple[str, ...],
+                ext_destination: tuple[str, ...],
+                ext_ton_amount: tuple[int, ...],
+                ext_payload: tuple[str, ...],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                ext_destination: tuple[str, ...],
                ext_ton_amount: tuple[int, ...],
                ext_payload: tuple[str, ...],
🧰 Tools
🪛 Ruff (0.8.2)

112-112: Use tuple instead of Tuple for type annotation

Replace with tuple

(UP006)


113-113: Use tuple instead of Tuple for type annotation

Replace with tuple

(UP006)


114-114: Use tuple instead of Tuple for type annotation

Replace with tuple

(UP006)


116-116: 🧹 Nitpick (assertive)

Return type modernization suggestion.
Same rationale as above. Use dict[str, str] if your environment permits it.

-) -> Dict[str, str]:
+) -> dict[str, str]:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                ) -> dict[str, str]:
🧰 Tools
🪛 Ruff (0.8.2)

116-116: Use dict instead of Dict for type annotation

Replace with dict

(UP006)


145-147: ⚠️ Potential issue

Typo and potential logic error detected.
signning_message is likely a typo; it should be signing_message. This could break your runtime flow.

-    assert resp.signning_message is not None
-    return {"signature": f"0x{resp.signature.hex()}", "signed_message": f"0x{resp.signning_message.hex()}"}
+    assert resp.signing_message is not None
+    return {"signature": f"0x{resp.signature.hex()}", "signed_message": f"0x{resp.signing_message.hex()}"}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    assert resp.signature is not None
    assert resp.signing_message is not None
    return {"signature": f"0x{resp.signature.hex()}", "signed_message": f"0x{resp.signing_message.hex()}"}
🧰 Tools
🪛 Ruff (0.8.2)

145-145: Use of assert detected

(S101)


146-146: Use of assert detected

(S101)


169-169: 🧹 Nitpick (assertive)

Use of legacy Dict.
Switch to dict for forward-friendly annotations.

-) -> Dict[str, str]:
+) -> dict[str, str]:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                ) -> dict[str, str]:
🧰 Tools
🪛 Ruff (0.8.2)

169-169: Use dict instead of Dict for type annotation

Replace with dict

(UP006)


18-18: 🧹 Nitpick (assertive)

Use built-in types.
Use dict and tuple from Python 3.9+ instead of Dict and Tuple if possible. It simplifies dependencies and aligns with modern Python.

- from typing import TYPE_CHECKING, Tuple, Dict
+ from typing import TYPE_CHECKING
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

from typing import TYPE_CHECKING
🧰 Tools
🪛 Ruff (0.8.2)

18-18: typing.Tuple is deprecated, use tuple instead

(UP035)


18-18: typing.Dict is deprecated, use dict instead

(UP035)


186-187: 🧹 Nitpick (assertive)

Asserts in production code.
Typically, assert is discouraged in production for error handling. Raise a custom exception or handle gracefully.

-    assert resp.signature is not None
-    return {"signature": f"0x{resp.signature.hex()}"}
+    if resp.signature is None:
+        raise ValueError("Missing signature")
+    return {"signature": f"0x{resp.signature.hex()}"}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if resp.signature is None:
        raise ValueError("Missing signature")
    return {"signature": f"0x{resp.signature.hex()}"}
🧰 Tools
🪛 Ruff (0.8.2)

186-186: Use of assert detected

(S101)

core/src/apps/cardano/sign_tx/multisig_signer.py (4)

50-50: 🧹 Nitpick (assertive)

Generic error message.
raise ProcessError("Invalid output") is concise, but consider clarifying which output or reason if possible.

🧰 Tools
🪛 Ruff (0.8.2)

50-50: Avoid specifying long messages outside the exception class

(TRY003)


57-57: 🧹 Nitpick (assertive)

Stake pool check.
Raising ProcessError is straightforward. Possibly combine all invalid cert reasons for better debugging.

🧰 Tools
🪛 Ruff (0.8.2)

57-57: Avoid specifying long messages outside the exception class

(TRY003)


59-59: 🧹 Nitpick (assertive)

Another invalid cert.
Same note as line 57. Grouping errors can help debugging.

🧰 Tools
🪛 Ruff (0.8.2)

59-59: Avoid specifying long messages outside the exception class

(TRY003)


80-80: 🧹 Nitpick (assertive)

Raise for invalid request.
Very direct. Might be helpful to show path or reason in the error for debugging.

🧰 Tools
🪛 Ruff (0.8.2)

80-80: Avoid specifying long messages outside the exception class

(TRY003)

core/src/apps/bitcoin/psbt/psbt.py (10)

1-19: 🧹 Nitpick (assertive)

Imports and type hints.
Consider using Python 3.9+ built-ins (dict, tuple, list) to reduce dependency on typing.

🧰 Tools
🪛 Ruff (0.8.2)

19-19: typing.Dict is deprecated, use dict instead

(UP035)


19-19: typing.Tuple is deprecated, use tuple instead

(UP035)


19-19: typing.List is deprecated, use list instead

(UP035)


19-19: typing.Set is deprecated, use set instead

(UP035)


22-50: 🧹 Nitpick (assertive)

deserialize_HDKeypath logic.
Code is clear. Checking key size and duplicates is good. Possibly use more specific exceptions beyond Exception.

🧰 Tools
🪛 Ruff (0.8.2)

25-25: Use dict instead of Dict for type annotation

Replace with dict

(UP006)


26-26: Use list instead of List for type annotation

Replace with list

(UP006)


39-41: Create your own exception

(TRY002)


39-41: Avoid specifying long messages outside the exception class

(TRY003)


40-40: Trailing comma missing

Add trailing comma

(COM812)


44-46: Create your own exception

(TRY002)


44-46: Avoid specifying long messages outside the exception class

(TRY003)


45-45: Trailing comma missing

Add trailing comma

(COM812)


146-420: 🧹 Nitpick (assertive)

deserialize is quite long.
Function is big. Consider splitting logic to smaller helpers for readability. Also, handle each error with custom exceptions if you need distinct details.

🧰 Tools
🪛 Ruff (0.8.2)

146-146: deserialize is too complex (81 > 10)

(C901)


152-152: Use set instead of Set for type annotation

Replace with set

(UP006)


158-158: Do not catch blind exception: Exception

(BLE001)


170-172: Create your own exception

(TRY002)


170-172: Avoid specifying long messages outside the exception class

(TRY003)


171-171: Trailing comma missing

Add trailing comma

(COM812)


173-173: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


174-174: Create your own exception

(TRY002)


174-174: Avoid specifying long messages outside the exception class

(TRY003)


181-183: Create your own exception

(TRY002)


181-183: Avoid specifying long messages outside the exception class

(TRY003)


182-182: Trailing comma missing

Add trailing comma

(COM812)


184-184: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


185-185: Create your own exception

(TRY002)


185-185: Avoid specifying long messages outside the exception class

(TRY003)


191-193: Create your own exception

(TRY002)


191-193: Avoid specifying long messages outside the exception class

(TRY003)


192-192: Trailing comma missing

Add trailing comma

(COM812)


196-198: Create your own exception

(TRY002)


196-198: Avoid specifying long messages outside the exception class

(TRY003)


197-197: Trailing comma missing

Add trailing comma

(COM812)


204-206: Create your own exception

(TRY002)


204-206: Avoid specifying long messages outside the exception class

(TRY003)


205-205: Trailing comma missing

Add trailing comma

(COM812)


207-207: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


208-208: Create your own exception

(TRY002)


208-208: Avoid specifying long messages outside the exception class

(TRY003)


213-215: Create your own exception

(TRY002)


213-215: Avoid specifying long messages outside the exception class

(TRY003)


214-214: Trailing comma missing

Add trailing comma

(COM812)


216-216: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


217-217: Create your own exception

(TRY002)


217-217: Avoid specifying long messages outside the exception class

(TRY003)


221-223: Create your own exception

(TRY002)


221-223: Avoid specifying long messages outside the exception class

(TRY003)


222-222: Trailing comma missing

Add trailing comma

(COM812)


224-224: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


225-225: Create your own exception

(TRY002)


225-225: Avoid specifying long messages outside the exception class

(TRY003)


231-233: Create your own exception

(TRY002)


231-233: Avoid specifying long messages outside the exception class

(TRY003)


232-232: Trailing comma missing

Add trailing comma

(COM812)


234-234: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


235-235: Create your own exception

(TRY002)


235-235: Avoid specifying long messages outside the exception class

(TRY003)


239-241: Create your own exception

(TRY002)


239-241: Avoid specifying long messages outside the exception class

(TRY003)


240-240: Trailing comma missing

Add trailing comma

(COM812)


242-242: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


243-245: Create your own exception

(TRY002)


243-245: Avoid specifying long messages outside the exception class

(TRY003)


244-244: Trailing comma missing

Add trailing comma

(COM812)


250-252: Create your own exception

(TRY002)


250-252: Avoid specifying long messages outside the exception class

(TRY003)


251-251: Trailing comma missing

Add trailing comma

(COM812)


253-253: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


254-254: Create your own exception

(TRY002)


254-254: Avoid specifying long messages outside the exception class

(TRY003)


257-257: Create your own exception

(TRY002)


257-257: Avoid specifying long messages outside the exception class

(TRY003)


261-263: Create your own exception

(TRY002)


261-263: Avoid specifying long messages outside the exception class

(TRY003)


262-262: Trailing comma missing

Add trailing comma

(COM812)


264-264: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


265-267: Create your own exception

(TRY002)


265-267: Avoid specifying long messages outside the exception class

(TRY003)


266-266: Trailing comma missing

Add trailing comma

(COM812)


270-270: Create your own exception

(TRY002)


270-270: Avoid specifying long messages outside the exception class

(TRY003)


273-273: Unnecessary pass statement

Remove unnecessary pass

(PIE790)


275-275: Create your own exception

(TRY002)


275-275: Avoid specifying long messages outside the exception class

(TRY003)


276-276: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


277-277: Create your own exception

(TRY002)


277-277: Avoid specifying long messages outside the exception class

(TRY003)


280-280: Create your own exception

(TRY002)


280-280: Avoid specifying long messages outside the exception class

(TRY003)


283-283: Unnecessary pass statement

Remove unnecessary pass

(PIE790)


285-287: Create your own exception

(TRY002)


285-287: Avoid specifying long messages outside the exception class

(TRY003)


286-286: Trailing comma missing

Add trailing comma

(COM812)


288-288: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


289-291: Create your own exception

(TRY002)


289-291: Avoid specifying long messages outside the exception class

(TRY003)


290-290: Trailing comma missing

Add trailing comma

(COM812)


294-294: Create your own exception

(TRY002)


294-294: Avoid specifying long messages outside the exception class

(TRY003)


297-297: Unnecessary pass statement

Remove unnecessary pass

(PIE790)


299-301: Create your own exception

(TRY002)


299-301: Avoid specifying long messages outside the exception class

(TRY003)


300-300: Trailing comma missing

Add trailing comma

(COM812)


302-302: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


303-305: Create your own exception

(TRY002)


303-305: Avoid specifying long messages outside the exception class

(TRY003)


304-304: Trailing comma missing

Add trailing comma

(COM812)


308-308: Create your own exception

(TRY002)


308-308: Avoid specifying long messages outside the exception class

(TRY003)


312-314: Create your own exception

(TRY002)


312-314: Avoid specifying long messages outside the exception class

(TRY003)


313-313: Trailing comma missing

Add trailing comma

(COM812)


315-315: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


316-318: Create your own exception

(TRY002)


316-318: Avoid specifying long messages outside the exception class

(TRY003)


317-317: Trailing comma missing

Add trailing comma

(COM812)


321-323: Create your own exception

(TRY002)


321-323: Avoid specifying long messages outside the exception class

(TRY003)


322-322: Trailing comma missing

Add trailing comma

(COM812)


324-324: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


325-327: Create your own exception

(TRY002)


325-327: Avoid specifying long messages outside the exception class

(TRY003)


326-326: Trailing comma missing

Add trailing comma

(COM812)


330-332: Create your own exception

(TRY002)


330-332: Avoid specifying long messages outside the exception class

(TRY003)


331-331: Trailing comma missing

Add trailing comma

(COM812)


333-333: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


334-336: Create your own exception

(TRY002)


334-336: Avoid specifying long messages outside the exception class

(TRY003)


335-335: Trailing comma missing

Add trailing comma

(COM812)


341-343: Create your own exception

(TRY002)


341-343: Avoid specifying long messages outside the exception class

(TRY003)


342-342: Trailing comma missing

Add trailing comma

(COM812)


344-344: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


345-347: Create your own exception

(TRY002)


345-347: Avoid specifying long messages outside the exception class

(TRY003)


346-346: Trailing comma missing

Add trailing comma

(COM812)


351-353: Create your own exception

(TRY002)


351-353: Avoid specifying long messages outside the exception class

(TRY003)


352-352: Trailing comma missing

Add trailing comma

(COM812)


354-354: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


355-357: Create your own exception

(TRY002)


355-357: Avoid specifying long messages outside the exception class

(TRY003)


356-356: Trailing comma missing

Add trailing comma

(COM812)


359-361: Create your own exception

(TRY002)


359-361: Avoid specifying long messages outside the exception class

(TRY003)


360-360: Trailing comma missing

Add trailing comma

(COM812)


364-364: Create your own exception

(TRY002)


364-364: Avoid specifying long messages outside the exception class

(TRY003)


371-373: Create your own exception

(TRY002)


371-373: Avoid specifying long messages outside the exception class

(TRY003)


372-372: Trailing comma missing

Add trailing comma

(COM812)


374-374: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


375-375: Create your own exception

(TRY002)


375-375: Avoid specifying long messages outside the exception class

(TRY003)


381-381: Unnecessary start argument in range

Remove start argument

(PIE808)


389-391: Create your own exception

(TRY002)


389-391: Avoid specifying long messages outside the exception class

(TRY003)


390-390: Trailing comma missing

Add trailing comma

(COM812)


392-392: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


393-395: Create your own exception

(TRY002)


393-395: Avoid specifying long messages outside the exception class

(TRY003)


394-394: Trailing comma missing

Add trailing comma

(COM812)


398-398: Create your own exception

(TRY002)


398-398: Avoid specifying long messages outside the exception class

(TRY003)


401-403: Create your own exception

(TRY002)


401-403: Avoid specifying long messages outside the exception class

(TRY003)


402-402: Trailing comma missing

Add trailing comma

(COM812)


404-404: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


405-407: Create your own exception

(TRY002)


405-407: Avoid specifying long messages outside the exception class

(TRY003)


406-406: Trailing comma missing

Add trailing comma

(COM812)


410-410: Create your own exception

(TRY002)


410-410: Avoid specifying long messages outside the exception class

(TRY003)


413-415: Create your own exception

(TRY002)


413-415: Avoid specifying long messages outside the exception class

(TRY003)


414-414: Trailing comma missing

Add trailing comma

(COM812)


428-576: 🧹 Nitpick (assertive)

serialize method.
Again, quite large. Splitting it would help maintainability. The logic seems correct though.

🧰 Tools
🪛 Ruff (0.8.2)

428-428: serialize is too complex (25 > 10)

(C901)


438-438: Trailing comma missing

Add trailing comma

(COM812)


451-451: Trailing comma missing

Add trailing comma

(COM812)


457-457: Trailing comma missing

Add trailing comma

(COM812)


463-463: Trailing comma missing

Add trailing comma

(COM812)


469-469: Trailing comma missing

Add trailing comma

(COM812)


480-480: Trailing comma missing

Add trailing comma

(COM812)


488-488: Trailing comma missing

Add trailing comma

(COM812)


496-496: Trailing comma missing

Add trailing comma

(COM812)


503-503: Trailing comma missing

Add trailing comma

(COM812)


513-513: Trailing comma missing

Add trailing comma

(COM812)


519-519: Trailing comma missing

Add trailing comma

(COM812)


525-525: Trailing comma missing

Add trailing comma

(COM812)


531-531: Trailing comma missing

Add trailing comma

(COM812)


539-539: Trailing comma missing

Add trailing comma

(COM812)


545-545: Trailing comma missing

Add trailing comma

(COM812)


556-556: Trailing comma missing

Add trailing comma

(COM812)


557-557: Trailing comma missing

Add trailing comma

(COM812)


564-564: Trailing comma missing

Add trailing comma

(COM812)


565-565: Trailing comma missing

Add trailing comma

(COM812)


619-727: 🧹 Nitpick (assertive)

deserialize in outputs.
Similar complexity suggestion: break it down if it grows more. The checks are consistent with the input code.

🧰 Tools
🪛 Ruff (0.8.2)

619-619: deserialize is too complex (33 > 10)

(C901)


625-625: Use set instead of Set for type annotation

Replace with set

(UP006)


631-631: Do not catch blind exception: Exception

(BLE001)


643-645: Create your own exception

(TRY002)


643-645: Avoid specifying long messages outside the exception class

(TRY003)


644-644: Trailing comma missing

Add trailing comma

(COM812)


646-646: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


647-649: Create your own exception

(TRY002)


647-649: Avoid specifying long messages outside the exception class

(TRY003)


648-648: Trailing comma missing

Add trailing comma

(COM812)


653-655: Create your own exception

(TRY002)


653-655: Avoid specifying long messages outside the exception class

(TRY003)


654-654: Trailing comma missing

Add trailing comma

(COM812)


656-656: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


657-659: Create your own exception

(TRY002)


657-659: Avoid specifying long messages outside the exception class

(TRY003)


658-658: Trailing comma missing

Add trailing comma

(COM812)


665-665: Create your own exception

(TRY002)


665-665: Avoid specifying long messages outside the exception class

(TRY003)


666-666: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


667-667: Create your own exception

(TRY002)


667-667: Avoid specifying long messages outside the exception class

(TRY003)


670-670: Create your own exception

(TRY002)


670-670: Avoid specifying long messages outside the exception class

(TRY003)


674-674: Create your own exception

(TRY002)


674-674: Avoid specifying long messages outside the exception class

(TRY003)


675-675: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


676-676: Create your own exception

(TRY002)


676-676: Avoid specifying long messages outside the exception class

(TRY003)


680-682: Create your own exception

(TRY002)


680-682: Avoid specifying long messages outside the exception class

(TRY003)


681-681: Trailing comma missing

Add trailing comma

(COM812)


683-683: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


684-686: Create your own exception

(TRY002)


684-686: Avoid specifying long messages outside the exception class

(TRY003)


685-685: Trailing comma missing

Add trailing comma

(COM812)


689-689: Create your own exception

(TRY002)


689-689: Avoid specifying long messages outside the exception class

(TRY003)


692-694: Create your own exception

(TRY002)


692-694: Avoid specifying long messages outside the exception class

(TRY003)


693-693: Trailing comma missing

Add trailing comma

(COM812)


695-695: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


696-698: Create your own exception

(TRY002)


696-698: Avoid specifying long messages outside the exception class

(TRY003)


697-697: Trailing comma missing

Add trailing comma

(COM812)


702-704: Create your own exception

(TRY002)


702-704: Avoid specifying long messages outside the exception class

(TRY003)


703-703: Trailing comma missing

Add trailing comma

(COM812)


705-705: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


706-706: Create your own exception

(TRY002)


706-706: Avoid specifying long messages outside the exception class

(TRY003)


712-712: Unnecessary start argument in range

Remove start argument

(PIE808)


720-722: Create your own exception

(TRY002)


720-722: Avoid specifying long messages outside the exception class

(TRY003)


721-721: Trailing comma missing

Add trailing comma

(COM812)


735-796: 🧹 Nitpick (assertive)

Output serialize.
Similar to input logic. Splitting or clarifying might help. But it works.

🧰 Tools
🪛 Ruff (0.8.2)

735-735: serialize is too complex (11 > 10)

(C901)


744-744: Trailing comma missing

Add trailing comma

(COM812)


750-750: Trailing comma missing

Add trailing comma

(COM812)


770-770: Trailing comma missing

Add trailing comma

(COM812)


781-781: Trailing comma missing

Add trailing comma

(COM812)


797-806: 🧹 Nitpick (assertive)

get_txout method.
Use of assert is flagged in production. If you want robust error handling, consider raising an exception.

🧰 Tools
🪛 Ruff (0.8.2)

803-803: Use of assert detected

(S101)


804-804: Use of assert detected

(S101)


842-1099: 🧹 Nitpick (assertive)

PSBT.deserialize.
Huge. Good functionality, but consider factoring. Also watch for the same custom exception suggestion.

🧰 Tools
🪛 Ruff (0.8.2)

842-842: deserialize is too complex (58 > 10)

(C901)


850-850: Create your own exception

(TRY002)


850-850: Avoid specifying long messages outside the exception class

(TRY003)


852-852: Use set instead of Set for type annotation

Replace with set

(UP006)


862-862: Do not catch blind exception: Exception

(BLE001)


876-876: Create your own exception

(TRY002)


876-876: Avoid specifying long messages outside the exception class

(TRY003)


877-877: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


878-878: Create your own exception

(TRY002)


878-878: Avoid specifying long messages outside the exception class

(TRY003)


887-889: Create your own exception

(TRY002)


887-889: Avoid specifying long messages outside the exception class

(TRY003)


888-888: Trailing comma missing

Add trailing comma

(COM812)


894-896: Create your own exception

(TRY002)


894-896: Avoid specifying long messages outside the exception class

(TRY003)


895-895: Trailing comma missing

Add trailing comma

(COM812)


897-897: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


898-900: Create your own exception

(TRY002)


898-900: Avoid specifying long messages outside the exception class

(TRY003)


899-899: Trailing comma missing

Add trailing comma

(COM812)


903-903: Create your own exception

(TRY002)


903-903: Avoid specifying long messages outside the exception class

(TRY003)


907-909: Create your own exception

(TRY002)


907-909: Avoid specifying long messages outside the exception class

(TRY003)


908-908: Trailing comma missing

Add trailing comma

(COM812)


910-910: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


911-913: Create your own exception

(TRY002)


911-913: Avoid specifying long messages outside the exception class

(TRY003)


912-912: Trailing comma missing

Add trailing comma

(COM812)


916-916: Create your own exception

(TRY002)


916-916: Avoid specifying long messages outside the exception class

(TRY003)


920-922: Create your own exception

(TRY002)


920-922: Avoid specifying long messages outside the exception class

(TRY003)


921-921: Trailing comma missing

Add trailing comma

(COM812)


923-923: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


924-924: Create your own exception

(TRY002)


924-924: Avoid specifying long messages outside the exception class

(TRY003)


929-931: Create your own exception

(TRY002)


929-931: Avoid specifying long messages outside the exception class

(TRY003)


930-930: Trailing comma missing

Add trailing comma

(COM812)


932-932: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


933-935: Create your own exception

(TRY002)


933-935: Avoid specifying long messages outside the exception class

(TRY003)


934-934: Trailing comma missing

Add trailing comma

(COM812)


940-942: Create your own exception

(TRY002)


940-942: Avoid specifying long messages outside the exception class

(TRY003)


941-941: Trailing comma missing

Add trailing comma

(COM812)


943-943: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


944-946: Create your own exception

(TRY002)


944-946: Avoid specifying long messages outside the exception class

(TRY003)


945-945: Trailing comma missing

Add trailing comma

(COM812)


949-949: Create your own exception

(TRY002)


949-949: Avoid specifying long messages outside the exception class

(TRY003)


953-955: Create your own exception

(TRY002)


953-955: Avoid specifying long messages outside the exception class

(TRY003)


954-954: Trailing comma missing

Add trailing comma

(COM812)


956-956: Unnecessary elif after raise statement

Remove unnecessary elif

(RET506)


957-959: Create your own exception

(TRY002)


957-959: Avoid specifying long messages outside the exception class

(TRY003)


958-958: Trailing comma missing

Add trailing comma

(COM812)


962-962: Create your own exception

(TRY002)


962-962: Avoid specifying long messages outside the exception class

(TRY003)


967-969: Create your own exception

(TRY002)


967-969: Avoid specifying long messages outside the exception class

(TRY003)


968-968: Trailing comma missing

Add trailing comma

(COM812)


979-979: Create your own exception

(TRY002)


979-979: Avoid specifying long messages outside the exception class

(TRY003)


982-982: Create your own exception

(TRY002)


982-982: Avoid specifying long messages outside the exception class

(TRY003)


984-986: Create your own exception

(TRY002)


984-986: Avoid specifying long messages outside the exception class

(TRY003)


985-985: Trailing comma missing

Add trailing comma

(COM812)


988-988: Create your own exception

(TRY002)


988-988: Avoid specifying long messages outside the exception class

(TRY003)


990-990: Create your own exception

(TRY002)


990-990: Avoid specifying long messages outside the exception class

(TRY003)


992-992: Create your own exception

(TRY002)


992-992: Avoid specifying long messages outside the exception class

(TRY003)


996-996: Create your own exception

(TRY002)


996-996: Avoid specifying long messages outside the exception class

(TRY003)


1000-1000: Create your own exception

(TRY002)


1000-1000: Avoid specifying long messages outside the exception class

(TRY003)


1002-1002: Create your own exception

(TRY002)


1002-1002: Avoid specifying long messages outside the exception class

(TRY003)


1004-1004: Create your own exception

(TRY002)


1004-1004: Avoid specifying long messages outside the exception class

(TRY003)


1007-1007: Create your own exception

(TRY002)


1007-1007: Avoid specifying long messages outside the exception class

(TRY003)


1027-1027: Create your own exception

(TRY002)


1027-1027: Avoid specifying long messages outside the exception class

(TRY003)


1030-1032: Create your own exception

(TRY002)


1030-1032: Avoid specifying long messages outside the exception class

(TRY003)


1031-1031: Trailing comma missing

Add trailing comma

(COM812)


1037-1037: Loop control variable i not used within loop body

(B007)


1045-1047: Create your own exception

(TRY002)


1045-1047: Avoid specifying long messages outside the exception class

(TRY003)


1046-1046: Trailing comma missing

Add trailing comma

(COM812)


1070-1070: Use of assert detected

(S101)


1145-1176: 🧹 Nitpick (assertive)

compute_lock_time.
Slightly big, but logic is readable. Consider splitting time vs. height lock checks.

🧰 Tools
🪛 Ruff (0.8.2)

1145-1145: compute_lock_time is too complex (11 > 10)

(C901)


1158-1158: Create your own exception

(TRY002)


1158-1158: Avoid specifying long messages outside the exception class

(TRY003)


1162-1162: Create your own exception

(TRY002)


1162-1162: Avoid specifying long messages outside the exception class

(TRY003)


1186-1221: 🧹 Nitpick (assertive)

Constructing an unsigned tx.
Asserts again. Prefer raising an exception if these are critical.

🧰 Tools
🪛 Ruff (0.8.2)

1195-1195: Use of assert detected

(S101)


1202-1202: Use of assert detected

(S101)


1203-1203: Use of assert detected

(S101)


1204-1204: Use of assert detected

(S101)


1214-1214: Use of assert detected

(S101)

common/defs/evm_tokens/1.json (2)

160-185: ⚠️ Potential issue

Duplicated token ID but different symbol.

The new POL token uses the same _id as MATIC (62e8a3d28edb7c3c91a5586b). Fix this to avoid conflicts.

-      "_id": "62e8a3d28edb7c3c91a5586b",
+      "_id": "unique_id_for_pol_token",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    {
      "_id": "unique_id_for_pol_token",
      "name": "Polygon",
      "symbol": "POL",
      "address": "0x455e53CBB86018Ac2B8092FdCd39d8444aFFC3F6",
      "decimals": 18,
      "logoURI": "https://common.onekey-asset.com/token/evm-1/0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0.jpg",
      "impl": "evm",
      "status": "LISTED",
      "verified": true,
      "security": false,
      "addToIndex": false,
      "chainId": "1",
      "source": [
        "sushi",
        "Uniswap Labs Default",
        "Coingecko"
      ],
      "checked": true,
      "coingeckoId": "matic-network",
      "swftId": "MATIC",
      "createdAt": "2022-08-02T04:10:58.228Z",
      "updatedAt": "2022-11-16T13:02:51.357Z",
      "__v": 0,
      "marketCap": "6126893790.915463"
    },

1293-1317: 🧹 Nitpick (assertive)

💡 Verification agent

🧩 Analysis chain

Missing important token metadata.

The HSK token has empty values for several fields including logoURI, marketCap, and timestamps.

Add the missing metadata for better token display:

-      "_id": "",
+      "_id": "unique_id_for_hsk_token",
-      "logoURI": "",
+      "logoURI": "https://common.onekey-asset.com/token/evm-1/0xe7c6bf469e97eeb0bfb74c8dbff5bd47d4c1c98a.png",
-      "createdAt": "",
+      "createdAt": "2023-03-22T00:00:00.000Z",
-      "updatedAt": "",
+      "updatedAt": "2023-03-22T00:00:00.000Z",
-      "coingeckoId": "",
+      "coingeckoId": "hashkey-token",

🌐 Web query:

Is the HSK token (HashKey Platform Token) listed on CoinGecko?

💡 Result:

Yes, the HSK token (HashKey Platform Token) is listed on CoinGecko. The platform provides detailed information about HSK, including its current price, trading volume, historical price charts, and market data. As of the latest data, HSK is trading at $0.8187 with a 24-hour trading volume of $2.17 million[4][7]. CoinGecko also lists the exchanges where HSK can be traded, such as Gate.io, HashKey Global, and KuCoin, along with trading pairs like HSK/USDT[4][7]. Additionally, historical price data shows HSK reached an all-time high of $2.56 in December 2024 and an all-time low of $0.7101 in February 2025[4][7].

Citations:


Update HSK Token Metadata

The HSK token (HashKey Platform Token) is listed on CoinGecko, but its metadata is incomplete. Several fields are currently empty, including:

  • _id
  • logoURI
  • createdAt and updatedAt
  • coingeckoId
  • marketCap

Please update these fields to incorporate a unique identifier, a valid logo URL, proper timestamps, and the correct CoinGecko ID. This will improve consistency and token display.

For example:

-      "_id": "",
+      "_id": "unique_id_for_hsk_token",
-      "logoURI": "",
+      "logoURI": "https://common.onekey-asset.com/token/evm-1/0xe7c6bf469e97eeb0bfb74c8dbff5bd47d4c1c98a.png",
-      "createdAt": "",
+      "createdAt": "2023-03-22T00:00:00.000Z",
-      "updatedAt": "",
+      "updatedAt": "2023-03-22T00:00:00.000Z",
-      "coingeckoId": "",
+      "coingeckoId": "hashkey-token",

Updating these fields is required for proper integration.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    {
      "_id": "unique_id_for_hsk_token",
      "name": "HashKey Platform Token",
      "symbol": "HSK",
      "address": "0xe7c6bf469e97eeb0bfb74c8dbff5bd47d4c1c98a",
      "decimals": 18,
      "logoURI": "https://common.onekey-asset.com/token/evm-1/0xe7c6bf469e97eeb0bfb74c8dbff5bd47d4c1c98a.png",
      "impl": "evm",
      "status": "LISTED",
      "verified": true,
      "security": false,
      "addToIndex": false,
      "chainId": "1",
      "source": [
        "sushi",
        "Coingecko"
      ],
      "checked": true,
      "coingeckoId": "hashkey-token",
      "swftId": "",
      "createdAt": "2023-03-22T00:00:00.000Z",
      "updatedAt": "2023-03-22T00:00:00.000Z",
      "__v": 0,
      "marketCap": ""
    }
core/src/apps/cardano/seed.py (2)

14-19: 🧹 Nitpick (assertive)

Updated type imports.

Added more specific type imports for better typing.

Import from collections.abc instead:

-    from typing import Awaitable, Callable, TypeVar
+    from collections.abc import Awaitable
+    from typing import Callable, TypeVar
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    from collections.abc import Awaitable
    from typing import Callable, TypeVar

    from trezor import messages

    from apps.common.keychain import Handler, MsgOut
    from apps.common.paths import Bip32Path
🧰 Tools
🪛 Ruff (0.8.2)

14-14: Import from collections.abc instead: Awaitable

Import from collections.abc

(UP035)


53-53: 🧹 Nitpick (assertive)

❓ Verification inconclusive

Added force_strict parameter.

New parameter controls path verification strictness.

Consider using keyword-only argument:

-    def verify_path(self, path: Bip32Path, _force_strict: bool = True) -> None:
+    def verify_path(self, path: Bip32Path, *, _force_strict: bool = True) -> None:

🏁 Script executed:

#!/bin/bash
# Check how _force_strict is used in other places

grep -r "_force_strict" --include="*.py" core/src/apps/

Length of output: 276


Force Strict Parameter Verified & Keyword-Only Suggestion

  • The _force_strict parameter is consistently applied across modules (both Cardano and Polkadot).

  • The new parameter integration works as intended.

  • As a refinement, consider updating the signature to use a keyword-only argument:

    -    def verify_path(self, path: Bip32Path, _force_strict: bool = True) -> None:
    +    def verify_path(self, path: Bip32Path, *, _force_strict: bool = True) -> None:

This is a good-to-have refactor that enhances clarity.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def verify_path(self, path: Bip32Path, *, _force_strict: bool = True) -> None:
🧰 Tools
🪛 Ruff (0.8.2)

53-53: Boolean-typed positional argument in function definition

(FBT001)


53-53: Boolean default positional argument in function definition

(FBT002)

core/src/apps/bitcoin/psbt/tx.py (8)

36-39: 🧹 Nitpick (assertive)

Add a return annotation to __init__.
Add -> None since constructors don't return values.

- def __init__(self, hash: int = 0, n: int = 0xFFFFFFFF):
+ def __init__(self, hash: int = 0, n: int = 0xFFFFFFFF) -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def __init__(self, hash: int = 0, n: int = 0xFFFFFFFF) -> None:
        self.hash = hash
        self.n = n
🧰 Tools
🪛 Ruff (0.8.2)

36-36: Missing return type annotation for special method __init__

Add return type annotation: None

(ANN204)


192-195: 🧹 Nitpick (assertive)

Streamline with all().
Use a more concise check.

- for x in self.vtxinwit:
-     if not x.is_null():
-         return False
- return True
+ return all(x.is_null() for x in self.vtxinwit)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        return all(x.is_null() for x in self.vtxinwit)
🧰 Tools
🪛 Ruff (0.8.2)

192-195: Use return all(x.is_null() for x in self.vtxinwit) instead of for loop

Replace with return all(x.is_null() for x in self.vtxinwit)

(SIM110)


57-62: 🧹 Nitpick (assertive)

Add a return annotation to __init__.
Include -> None for clarity.

- def __init__(
-     self,
-     outpoint: COutPoint | None = None,
-     scriptSig: bytes = b"",
-     nSequence: int = 0,
- ):
+ def __init__(
+     self,
+     outpoint: COutPoint | None = None,
+     scriptSig: bytes = b"",
+     nSequence: int = 0,
+ ) -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def __init__(
        self,
        outpoint: COutPoint | None = None,
        scriptSig: bytes = b"",
        nSequence: int = 0,
    ) -> None:
🧰 Tools
🪛 Ruff (0.8.2)

57-57: Missing return type annotation for special method __init__

Add return type annotation: None

(ANN204)


92-95: 🧹 Nitpick (assertive)

Add a return annotation to __init__.
Add -> None to specify no return value.

- def __init__(self, nValue: int = 0, scriptPubKey: bytes = b""):
+ def __init__(self, nValue: int = 0, scriptPubKey: bytes = b"") -> None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def __init__(self, nValue: int = 0, scriptPubKey: bytes = b"") -> None:
        self.nValue = nValue
        self.scriptPubKey = scriptPubKey
🧰 Tools
🪛 Ruff (0.8.2)

92-92: Missing return type annotation for special method __init__

Add return type annotation: None

(ANN204)


145-147: 🧹 Nitpick (assertive)

Simplify the return statement.
Use return not self.stack for clarity.

- if self.stack:
-     return False
- return True
+ return not self.stack
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        return not self.stack
🧰 Tools
🪛 Ruff (0.8.2)

145-147: Return the condition not self.stack directly

Replace with return not self.stack

(SIM103)


279-279: 🧹 Nitpick (assertive)

Make the boolean argument keyword-only.
Boolean positional parameters can be confusing.

- def calc_sha256(self, with_witness: bool = False) -> int | None:
+ def calc_sha256(self, *, with_witness: bool = False) -> int | None:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    def calc_sha256(self, *, with_witness: bool = False) -> int | None:
🧰 Tools
🪛 Ruff (0.8.2)

279-279: Boolean-typed positional argument in function definition

(FBT001)


279-279: Boolean default positional argument in function definition

(FBT002)


88-88: 🧹 Nitpick (assertive)

Use an explicit conversion flag.
Replace :i with something like :d or :x.

- return f"CTxIn(..., nSequence={self.nSequence:i})"
+ return f"CTxIn(..., nSequence={self.nSequence:d})"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            return f"CTxIn(prevout={repr(self.prevout)}, scriptSig={binascii.hexlify(self.scriptSig).decode()}, nSequence={self.nSequence:d})"
🧰 Tools
🪛 Ruff (0.8.2)

88-88: Use explicit conversion flag

Replace with conversion flag

(RUF010)


295-295: 🧹 Nitpick (assertive)

Use explicit conversion flags for integers.
Replace :i with :d or :x.

- return f"CTransaction(... nLockTime={self.nLockTime:i})"
+ return f"CTransaction(... nLockTime={self.nLockTime:d})"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            return f"CTransaction(nVersion={self.nVersion:i} vin={repr(self.vin)} vout={repr(self.vout)} wit={repr(self.wit)} nLockTime={self.nLockTime:d})"
🧰 Tools
🪛 Ruff (0.8.2)

295-295: Use explicit conversion flag

Replace with conversion flag

(RUF010)


295-295: Use explicit conversion flag

Replace with conversion flag

(RUF010)


295-295: Use explicit conversion flag

Replace with conversion flag

(RUF010)

core/src/apps/bitcoin/bip322_simple.py (2)

87-87: 🧹 Nitpick (assertive)

Use a keyword-only argument and add a trailing comma.
Boolean positional parameters can be unclear, and a trailing comma eases future diffs.

- def sighash_bip143(message: bytes, script_pub: bytes, pubkeyhash: bytes, sign_hash_double: bool = True) -> bytes:
+ def sighash_bip143(
+     message: bytes,
+     script_pub: bytes,
+     pubkeyhash: bytes,
+     *,
+     sign_hash_double: bool = True,
+ ) -> bytes:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

def sighash_bip143(
    message: bytes,
    script_pub: bytes,
    pubkeyhash: bytes,
    *,
    sign_hash_double: bool = True,
) -> bytes:
    # function implementation goes here
🧰 Tools
🪛 Ruff (0.8.2)

87-87: Boolean-typed positional argument in function definition

(FBT001)


87-87: Boolean default positional argument in function definition

(FBT002)


87-87: Trailing comma missing

Add trailing comma

(COM812)


65-65: 🧹 Nitpick (assertive)

Add a trailing comma.
It helps keep diffs clean.

- writers.write_bytes_fixed(
-     h_sigmsg, h_scriptpubkeys.get_digest(), writers.TX_HASH_SIZE
- )
+ writers.write_bytes_fixed(
+     h_sigmsg, h_scriptpubkeys.get_digest(), writers.TX_HASH_SIZE,
+ )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

writers.write_bytes_fixed(
    h_sigmsg, h_scriptpubkeys.get_digest(), writers.TX_HASH_SIZE,
)
🧰 Tools
🪛 Ruff (0.8.2)

65-65: Trailing comma missing

Add trailing comma

(COM812)

core/src/apps/cardano/helpers/paths.py (1)

3-3: 🧹 Nitpick (assertive)

Remove unused import.
We don't use unharden. Let's tidy it up.

- from apps.common.paths import HARDENED, PathSchema, unharden  # noqa: F401
+ from apps.common.paths import HARDENED, PathSchema  # noqa: F401
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

from apps.common.paths import HARDENED, PathSchema  # noqa: F401
core/src/apps/cardano/addresses.py (3)

79-79: 🧹 Nitpick (assertive)

Add Trailing Commas
Ruff suggests trailing commas for clearer diffs and improved readability.

Apply this diff at each relevant spot:

- _validate_base_address_staking_info(
-     address_n_staking, parameters.staking_key_hash
- )
+ _validate_base_address_staking_info(
+     address_n_staking, parameters.staking_key_hash,
+ )

(Repeat for similar lines at 85, 268, 302.)

Also applies to: 85-85, 268-268, 302-302

🧰 Tools
🪛 Ruff (0.8.2)

79-79: Trailing comma missing

Add trailing comma

(COM812)


279-279: 🧹 Nitpick (assertive)

Exception Message Format
Consider using shorter messages or referencing a constant to avoid duplicating it in the exception.

🧰 Tools
🪛 Ruff (0.8.2)

279-279: Avoid specifying long messages outside the exception class

(TRY003)


417-417: 🧹 Nitpick (assertive)

Unnecessary Elif
You can remove the elif after a return. It simplifies reading.

    if parameters.staking_key_hash:
        return parameters.staking_key_hash
-   elif parameters.address_n_staking:
+   if parameters.address_n_staking:
       return get_public_key_hash(keychain, parameters.address_n_staking)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if parameters.staking_key_hash:
        return parameters.staking_key_hash
    if parameters.address_n_staking:
        return get_public_key_hash(keychain, parameters.address_n_staking)
🧰 Tools
🪛 Ruff (0.8.2)

417-417: Unnecessary elif after return statement

Remove unnecessary elif

(RET505)

core/src/apps/common/paths.py (3)

8-8: 🧹 Nitpick (assertive)

Change Imports to collections.abc
Use from collections.abc import Collection, Container, Iterable, Sequence instead.

-from typing import Any, Callable, Collection, Container, Iterable, Sequence, TypeVar
+from typing import Any, Callable, TypeVar
+from collections.abc import Collection, Container, Iterable, Sequence

Also applies to: 10-10

🧰 Tools
🪛 Ruff (0.8.2)

8-8: Import from collections.abc instead: Collection, Container, Iterable, Sequence

Import from collections.abc

(UP035)


24-24: 🧹 Nitpick (assertive)

Boolean Default Parameter
Consider replacing boolean parameters with named arguments or dedicated “strictness” enums.

- def verify_path(self, path: Bip32Path, force_strict: bool = True) -> None:
+ def verify_path(self, path: Bip32Path, *, force_strict: bool = True) -> None:

Also applies to: 342-342

🧰 Tools
🪛 Ruff (0.8.2)

24-24: Boolean-typed positional argument in function definition

(FBT001)


24-24: Boolean default positional argument in function definition

(FBT002)


379-379: 🧹 Nitpick (assertive)

Combine Endswith Checks
Use a tuple in endswith for clarity and efficiency.

-if item.endswith("'") or item.endswith("h") or item.endswith("H"):
+if item.endswith(("'", "h", "H")):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

-        if item.endswith("'") or item.endswith("h") or item.endswith("H"):
+        if item.endswith(("'", "h", "H")):
🧰 Tools
🪛 Ruff (0.8.2)

379-379: Call endswith once with a tuple

Merge into a single endswith call

(PIE810)

core/src/apps/bitcoin/psbt/script.py (2)

65-65: 🧹 Nitpick (assertive)

Use Built-in tuples
Use lowercase tuple instead of Tuple in type hints for compliance with newer Python versions.

- def is_witness(script: bytes) -> Tuple[bool, int, bytes]:
+ def is_witness(script: bytes) -> tuple[bool, int, bytes]:

- def parse_multisig(script: bytes) -> Tuple[int, list[bytes]] | None:
+ def parse_multisig(script: bytes) -> tuple[int, list[bytes]] | None:

Also applies to: 134-134

🧰 Tools
🪛 Ruff (0.8.2)

65-65: Use tuple instead of Tuple for type annotation

Replace with tuple

(UP006)


6-6: 🧹 Nitpick (assertive)

Remove Unused Pass
No-op statements add clutter.

- pass
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.


🧰 Tools
🪛 Ruff (0.8.2)

6-6: Unnecessary pass statement

Remove unnecessary pass

(PIE790)

core/src/apps/cardano/certificates.py (2)

36-36: 🧹 Nitpick (assertive)

Inlining imports in functions.
Consider moving these imports to the module scope if possible. In MicroPython contexts, inlined imports may be used intentionally. No functional issues here.

Also applies to: 38-38, 40-40


53-53: 🧹 Nitpick (assertive)

Use shorter or custom exception messages.
These lines raise generic ProcessError("Invalid ..."). Consider defining a specialized exception or at least using concise messages curated in a constant. It helps unify and shorten repeated error messages.

Also applies to: 55-55, 59-59, 69-69, 73-73, 80-80, 90-90, 122-122

core/src/apps/cardano/sign_tx/ordinary_signer.py (1)

53-53: 🧹 Nitpick (assertive)

Consider shorter errors or a dedicated exception.
Repeating "Invalid certificate" or "Invalid withdrawal" might be shortened or centralized. This can reduce repeated literals.

Also applies to: 55-55, 60-60, 76-76

🧰 Tools
🪛 Ruff (0.8.2)

53-53: Avoid specifying long messages outside the exception class

(TRY003)

core/src/trezor/lvglui/i18n/locales/ja.py (1)

846-877: 🧹 Nitpick (assertive)

Consider standard ASCII punctuation.
Some lines use fullwidth question marks, which might cause confusion.

🧰 Tools
🪛 Ruff (0.8.2)

850-850: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


850-850: String contains ambiguous (FULLWIDTH COLON). Did you mean : (COLON)?

(RUF001)


850-850: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


852-852: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


852-852: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


867-867: String contains ambiguous (FULLWIDTH QUESTION MARK). Did you mean ? (QUESTION MARK)?

(RUF001)

core/src/apps/bitcoin/psbt/serialize.py (3)

1-20: 🛠️ Refactor suggestion

Consider simpler usage of built-in types.
Use list instead of typing.List, and import Sequence from collections.abc.

🧰 Tools
🪛 Ruff (0.8.2)

5-5: Import from collections.abc instead: Sequence

Import from collections.abc

(UP035)


5-5: typing.List is deprecated, use list instead

(UP035)


152-165: 🛠️ Refactor suggestion

Deserialization of string array.
Check the usage of List vs list.

🧰 Tools
🪛 Ruff (0.8.2)

152-152: Use list instead of List for type annotation

Replace with list

(UP006)


167-178: 🧹 Nitpick (assertive)

Serializing string vectors is consistent.
Same note on List usage.

🧰 Tools
🪛 Ruff (0.8.2)

167-167: Use list instead of List for type annotation

Replace with list

(UP006)

core/src/apps/cardano/auxiliary_data.py (1)

16-17: 🧹 Nitpick (assertive)

Type definitions
Consider using typed NamedTuples or classes for clarity.

core/src/trezor/messages.py (2)

27-29: 🧹 Nitpick (assertive)

Consider cleaning up unused noqa directives.

The static analysis tool flags these imports as having unnecessary noqa: F401 directives. These can be safely removed if they're not needed.

-    from trezor.enums import CardanoCVoteRegistrationFormat  # noqa: F401
+    from trezor.enums import CardanoCVoteRegistrationFormat
-    from trezor.enums import CardanoDRepType  # noqa: F401
+    from trezor.enums import CardanoDRepType

And similarly for the Solana enums:

-    from trezor.enums import SolanaOffChainMessageFormat  # noqa: F401
+    from trezor.enums import SolanaOffChainMessageFormat
-    from trezor.enums import SolanaOffChainMessageVersion  # noqa: F401
+    from trezor.enums import SolanaOffChainMessageVersion

Also applies to: 61-62

🧰 Tools
🪛 Ruff (0.8.2)

27-27: Unused noqa directive (unused: F401)

Remove unused noqa directive

(RUF100)


28-28: Unused noqa directive (unused: F401)

Remove unused noqa directive

(RUF100)


29-29: Unused noqa directive (unused: F401)

Remove unused noqa directive

(RUF100)


1166-1166: 🧹 Nitpick (assertive)

Static typing could be improved in type check methods.

The is_type_of methods have dynamically typed expressions (using Any). Consider adding more specific type annotations if your team's coding standards emphasize strict typing.

Also applies to: 1180-1180, 1836-1836, 1900-1900, 1928-1928, 7374-7374, 7390-7390, 7406-7406

🧰 Tools
🪛 Ruff (0.8.2)

1166-1166: Dynamically typed expressions (typing.Any) are disallowed in msg

(ANN401)

core/src/apps/cardano/layout.py (4)

219-219: 🧹 Nitpick (assertive)

Boolean default argument
chunkify: bool = False can be passed as a keyword parameter for clarity.


357-376: 🧹 Nitpick (assertive)

CVote payment credentials
Handles two booleans (show_both_credentials, show_payment_warning). Code flow is clear. Consider using keyword-only parameters for booleans if you like more clarity.

🧰 Tools
🪛 Ruff (0.8.2)

361-361: Boolean-typed positional argument in function definition

(FBT001)


362-362: Boolean-typed positional argument in function definition

(FBT001)


366-366: Trailing comma missing

Add trailing comma

(COM812)


437-438: 🧹 Nitpick (assertive)

Boolean typed positional arguments
is_collateral_return: bool = False and similar might be clearer as keyword-only. No functional issues though.

Also applies to: 442-443


187-203: 🧹 Nitpick (assertive)

Unused arguments
ctx and title are unused. This function returns True unconditionally. If more logic is pending, implement or remove the unused parameters to keep the code clean.

 async def show_tx_init(ctx: wire.Context, title: str) -> bool:
-    # ...
     return True

+    # Or remove them if unneeded:
+async def show_tx_init() -> bool:
+    return True

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

187-187: Unused function argument: ctx

(ARG001)


187-187: Unused function argument: title

(ARG001)

@somebodyLi somebodyLi merged commit bbd533a into touch Mar 3, 2025
11 checks passed
@somebodyLi somebodyLi deleted the 4.10 branch March 3, 2025 10:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants