# Buggy code
def pairing_dialog(self):
    def pairing_step(code: str, device_response: Callable[[], bool]) -> bool:
        msg = "Please compare and confirm the pairing code on your BitBox02:\n" + code
        self.handler.show_message(msg)
        try:
            res = device_response()
        except:
            # Close the hid device on exception
            with self.device_manager().hid_lock:
                hid_device.close()
            raise
        finally:
            self.handler.finished()
        return res

    def exists_remote_static_pubkey(pubkey: bytes) -> bool:
        bitbox02_config = self.config.get("bitbox02")
        noise_keys = bitbox02_config.get("remote_static_noise_keys")
        if noise_keys is not None:
            if pubkey.hex() in [noise_key for noise_key in noise_keys]:
                return True
        return False

    def set_remote_static_pubkey(pubkey: bytes) -> None:
        if not exists_remote_static_pubkey(pubkey):
            bitbox02_config = self.config.get("bitbox02")
            if bitbox02_config.get("remote_static_noise_keys") is not None:
                bitbox02_config["remote_static_noise_keys"].append(pubkey.hex())
            else:
                bitbox02_config["remote_static_noise_keys"] = [pubkey.hex()]
            self.config.set_key("bitbox02", bitbox02_config)

    def get_noise_privkey() -> Optional[bytes]:
        bitbox02_config = self.config.get("bitbox02")
        privkey = bitbox02_config.get("noise_privkey")
        if privkey is not None:
            return bytes.fromhex(privkey)
        return None

    def set_noise_privkey(privkey: bytes) -> None:
        bitbox02_config = self.config.get("bitbox02")
        bitbox02_config["noise_privkey"] = privkey.hex()
        self.config.set_key("bitbox02", bitbox02_config)

    def attestation_warning() -> None:
        self.handler.show_error(
            "The BitBox02 attestation failed.\nTry reconnecting the BitBox02.\nWarning: The device might not be genuine, if the\n problem persists please contact Shift support.",
            blocking=True,
        )

    class NoiseConfig(bitbox_api_protocol.BitBoxNoiseConfig):
        """NoiseConfig extends BitBoxNoiseConfig"""

        def show_pairing(self, code: str, device_response: Callable[[], bool]) -> bool:
            return pairing_step(code, device_response)

        def attestation_check(self, result: bool) -> None:
            if not result:
                attestation_warning()

        def contains_device_static_pubkey(self, pubkey: bytes) -> bool:
            return exists_remote_static_pubkey(pubkey)

        def add_device_static_pubkey(self, pubkey: bytes) -> None:
            return set_remote_static_pubkey(pubkey)

        def get_app_static_privkey(self) -> Optional[bytes]:
            return get_noise_privkey()

        def set_app_static_privkey(self, privkey: bytes) -> None:
            return set_noise_privkey(privkey)

    if self.bitbox02_device is None:
        with self.device_manager().hid_lock:
            hid_device = hid.device()
            hid_device.open_path(self.bitbox_hid_info["path"])

        bitbox02_device = bitbox02.BitBox02(
            transport=u2fhid.U2FHid(hid_device),
            device_info=self.bitbox_hid_info,
            noise_config=NoiseConfig(),
        )
        try:
            bitbox02_device.check_min_version()
        except FirmwareVersionOutdatedException:
            raise
        self.bitbox02_device = bitbox02_device

    self.fail_if_not_initialized()


# Traceback (OSError)
$ ~/Downloads/apps/electrum-4.0.2-x86_64.AppImage --testnet
Warning: Ignoring XDG_SESSION_TYPE=wayland on Gnome. Use QT_QPA_PLATFORM=wayland to run on Wayland anyway.
E | plugin.DeviceMgr | failed to create client for bitbox02 at b'0001:0009:01': Exception('No BitBox02 detected')
E | plugins.coldcard.coldcard.Coldcard_KeyStore |
Traceback (most recent call last):
File "/tmp/.mount_electrcFBIsQ/usr/lib/python3.7/site-packages/electrum/plugins/coldcard/coldcard.py", line 383, in sign_transaction
resp = client.sign_transaction_poll()
File "/tmp/.mount_electrcFBIsQ/usr/lib/python3.7/site-packages/electrum/plugins/coldcard/coldcard.py", line 233, in sign_transaction_poll
return self.dev.send_recv(CCProtocolPacker.get_signed_txn(), timeout=None)
File "/tmp/.mount_electrcFBIsQ/usr/lib/python3.7/site-packages/ckcc/client.py", line 139, in send_recv
buf = self.dev.read(64, timeout_ms=(timeout or 0))
File "hid.pyx", line 123, in hid.device.read
OSError: read error
double free or corruption (fasttop)
Aborted

# Fixed code
def pairing_dialog(self):
    def pairing_step(code: str, device_response: Callable[[], bool]) -> bool:
        msg = "Please compare and confirm the pairing code on your BitBox02:\n" + code
        self.handler.show_message(msg)
        try:
            res = device_response()
        except:
            # Close the hid device on exception
            hid_device.close()
            raise
        finally:
            self.handler.finished()
        return res

    def exists_remote_static_pubkey(pubkey: bytes) -> bool:
        bitbox02_config = self.config.get("bitbox02")
        noise_keys = bitbox02_config.get("remote_static_noise_keys")
        if noise_keys is not None:
            if pubkey.hex() in [noise_key for noise_key in noise_keys]:
                return True
        return False

    def set_remote_static_pubkey(pubkey: bytes) -> None:
        if not exists_remote_static_pubkey(pubkey):
            bitbox02_config = self.config.get("bitbox02")
            if bitbox02_config.get("remote_static_noise_keys") is not None:
                bitbox02_config["remote_static_noise_keys"].append(pubkey.hex())
            else:
                bitbox02_config["remote_static_noise_keys"] = [pubkey.hex()]
            self.config.set_key("bitbox02", bitbox02_config)

    def get_noise_privkey() -> Optional[bytes]:
        bitbox02_config = self.config.get("bitbox02")
        privkey = bitbox02_config.get("noise_privkey")
        if privkey is not None:
            return bytes.fromhex(privkey)
        return None

    def set_noise_privkey(privkey: bytes) -> None:
        bitbox02_config = self.config.get("bitbox02")
        bitbox02_config["noise_privkey"] = privkey.hex()
        self.config.set_key("bitbox02", bitbox02_config)

    def attestation_warning() -> None:
        self.handler.show_error(
            "The BitBox02 attestation failed.\nTry reconnecting the BitBox02.\nWarning: The device might not be genuine, if the\n problem persists please contact Shift support.",
            blocking=True,
        )

    class NoiseConfig(bitbox_api_protocol.BitBoxNoiseConfig):
        """NoiseConfig extends BitBoxNoiseConfig"""

        def show_pairing(self, code: str, device_response: Callable[[], bool]) -> bool:
            return pairing_step(code, device_response)

        def attestation_check(self, result: bool) -> None:
            if not result:
                attestation_warning()

        def contains_device_static_pubkey(self, pubkey: bytes) -> bool:
            return exists_remote_static_pubkey(pubkey)

        def add_device_static_pubkey(self, pubkey: bytes) -> None:
            return set_remote_static_pubkey(pubkey)

        def get_app_static_privkey(self) -> Optional[bytes]:
            return get_noise_privkey()

        def set_app_static_privkey(self, privkey: bytes) -> None:
            return set_noise_privkey(privkey)

    if self.bitbox02_device is None:
        hid_device = hid.device()
        hid_device.open_path(self.bitbox_hid_info["path"])

        bitbox02_device = bitbox02.BitBox02(
            transport=u2fhid.U2FHid(hid_device),
            device_info=self.bitbox_hid_info,
            noise_config=NoiseConfig(),
        )
        try:
            bitbox02_device.check_min_version()
        except FirmwareVersionOutdatedException:
            raise
        self.bitbox02_device = bitbox02_device

    self.fail_if_not_initialized()