Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/onekeylib/src/onekeylib/protocol_v2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# This file is part of the OneKey Python library.
#
# Copyright (C) OneKey
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.

"""OneKey Protocol V2 client and session for Pro 2 and Neo.

- `client`: `OneKeyClientV2`, which sends requests and keeps the state below.
- `link`: message encoding over `proto_link` and link negotiation.
- `requests`: how each kind of request is treated (seedless, interactive, ...).
- `failures`: failure replies to exceptions.
- `sessions`: `SessionV2` and which wallet a passphrase setting opens.
- `workflow`: the signing exchange a wallet session keeps reserved.
"""

from __future__ import annotations

from .client import OneKeyClientV2
from .link import REQUIRED_V2_MESSAGES
from .sessions import SessionV2

__all__ = ["OneKeyClientV2", "REQUIRED_V2_MESSAGES", "SessionV2"]

Large diffs are not rendered by default.

72 changes: 72 additions & 0 deletions packages/onekeylib/src/onekeylib/protocol_v2/failures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# This file is part of the OneKey Python library.
#
# Copyright (C) OneKey
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.

"""Turn Protocol V2 failure replies into onekeylib exceptions."""

from __future__ import annotations

import re
import typing as t

from .. import exceptions, messages
from .requests import MANAGEMENT_REQUESTS, SESSION_REQUESTS

if t.TYPE_CHECKING:
from ..protobuf import MessageType

_FAILURE_PROCESS_ERROR = 5
# firmware-pro2: DeviceSessionErrorCode (session requests) and
# app/utils/protocol.py SUBCODE_USER_CANCELLED (wallet requests) both use 1.
_SUBCODE_USER_CANCELLED = 1
_SUBCODE_INVALID_SESSION = 2

# Older Protocol V2 firmware may omit the cancellation subcode. Keep the same
# narrow message fallback as packages/core DeviceCommands.ts.
_LEGACY_CANCEL_MESSAGE = re.compile(
r"^(?:cancel(?:led|ed)(?: on device)?|confirm dismissed|update cancel(?:led|ed)"
r"|user cancel(?:led|ed)(?:\s+.*)?)$",
re.IGNORECASE,
)


def is_cancel_failure(request: MessageType, failure: messages.V2Failure) -> bool:
if failure.code != _FAILURE_PROCESS_ERROR:
return False
if failure.subcode is None:
return bool(_LEGACY_CANCEL_MESSAGE.match((failure.message or "").strip()))
if failure.subcode == _SUBCODE_USER_CANCELLED:
return not isinstance(request, MANAGEMENT_REQUESTS)
return False


def failure_error(request: MessageType, resp: MessageType) -> exceptions.OneKeyException | None:
"""The exception for a failure reply to `request`, or None for any other reply.

`request` is the request that started the exchange: a reply to a ButtonAck
relay still answers that request.
"""
if isinstance(resp, messages.V2Failure):
if is_cancel_failure(request, resp):
return exceptions.Cancelled(resp.message or "Cancelled on device")
if (
isinstance(request, SESSION_REQUESTS)
and resp.code == _FAILURE_PROCESS_ERROR
and resp.subcode == _SUBCODE_INVALID_SESSION
):
return exceptions.InvalidSessionError(None)
return exceptions.OneKeyFailure(
messages.Failure(
code=messages.FailureType.ProcessError,
message=resp.message or f"OneKey V2 failure ({resp.code}:{resp.subcode})",
)
)
if isinstance(resp, messages.Failure):
if resp.code == messages.FailureType.ActionCancelled:
return exceptions.Cancelled(resp.message or "Cancelled on device")
return exceptions.OneKeyFailure(resp)
return None
85 changes: 85 additions & 0 deletions packages/onekeylib/src/onekeylib/protocol_v2/link.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# This file is part of the OneKey Python library.
#
# Copyright (C) OneKey
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.

"""One Protocol V2 link: message encoding over `proto_link` and its negotiation."""

from __future__ import annotations

import typing as t

from .. import exceptions, messages

if t.TYPE_CHECKING:
from ..mapping import ProtobufMapping
from ..protobuf import MessageType
from ..transport.protolink import ProtoLinkTransport

REQUIRED_V2_MESSAGES = frozenset({
messages.DeviceInfoGet.MESSAGE_WIRE_TYPE,
messages.DeviceStatusGet.MESSAGE_WIRE_TYPE,
messages.DeviceSessionGet.MESSAGE_WIRE_TYPE,
messages.DeviceSessionAskPin.MESSAGE_WIRE_TYPE,
messages.DeviceSessionAskPassphrase.MESSAGE_WIRE_TYPE,
})


class LinkState:
"""What the client negotiated on one transport link.

A link the transport replaced (a new `generation`) must negotiate again:
nothing agreed on the old link carries over.
"""

def __init__(self) -> None:
self.handshaked = False
self.eventless = False
# Transport generation the handshake/eventless negotiation belongs to.
self.generation: int | None = None

def reset(self) -> None:
self.handshaked = False
self.eventless = False
self.generation = None


def generation_of(transport: ProtoLinkTransport) -> int:
return getattr(transport, "generation", 0)


def check_protocol_info(proto: messages.ProtocolInfo) -> None:
if proto.version != 1 or not REQUIRED_V2_MESSAGES.issubset(proto.supported_messages):
raise exceptions.OneKeyException(
"Unsupported OneKey Protocol V2 firmware"
)


def write(transport: ProtoLinkTransport, mapping: ProtobufMapping, msg: MessageType) -> int:
"""Encode and send one message. Returns the frame sequence to await an ACK for."""
wire_type, payload = mapping.encode(msg)
return transport.write_message(wire_type, payload)


def read(
transport: ProtoLinkTransport,
mapping: ProtobufMapping,
*,
timeout: float | None,
cancelled: t.Callable[[], bool] | None,
expected_ack_seq: int | None,
) -> MessageType:
"""Read and decode one message."""
wire_type, payload = transport.read_message(
timeout=timeout,
cancelled=cancelled,
expected_ack_seq=expected_ack_seq,
)
try:
return mapping.decode(wire_type, payload)
except (ValueError, OSError, KeyError, EOFError) as e:
# A reply that does not decode leaves the exchange in an unknown state.
raise exceptions.ProtocolError(f"Malformed OneKey V2 reply (wire type {wire_type})") from e
53 changes: 53 additions & 0 deletions packages/onekeylib/src/onekeylib/protocol_v2/requests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# This file is part of the OneKey Python library.
#
# Copyright (C) OneKey
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.

"""How the Protocol V2 client treats each kind of request."""

from __future__ import annotations

from .. import messages

# Messages sent mid-workflow (e.g. during SignTx) that must not be interrupted
# by management status/session queries.
MID_WORKFLOW_MESSAGES = (messages.TxAck, messages.PaymentRequest, messages.ButtonAck)

# Management requests. Their Failure subcodes are not wallet-session subcodes,
# so subcode 1 does not mean cancellation for them.
MANAGEMENT_REQUESTS = (
messages.V2Ping,
messages.ProtocolInfoRequest,
messages.DeviceInfoGet,
messages.DeviceStatusGet,
)
SESSION_REQUESTS = (
messages.DeviceSessionGet,
messages.DeviceSessionAskPin,
messages.DeviceSessionAskPassphrase,
)
# Messages a seedless session may send: nothing here reaches a wallet seed.
# VerifyMessage checks a public address and signature only.
SEEDLESS_MESSAGES = (
messages.Cancel,
messages.LockDevice,
messages.VerifyMessage,
*MANAGEMENT_REQUESTS,
)

# Requests that can wait for the user on the device. A host cancel during one
# of them sends Cancel so the device leaves its prompt.
INTERACTIVE_REQUESTS = (
messages.DeviceSessionAskPin,
messages.DeviceSessionAskPassphrase,
messages.GetPublicKey,
messages.GetAddress,
messages.SignMessage,
messages.VerifyMessage,
messages.SignTx,
messages.TxAck,
messages.ButtonAck,
)
130 changes: 130 additions & 0 deletions packages/onekeylib/src/onekeylib/protocol_v2/sessions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# This file is part of the OneKey Python library.
#
# Copyright (C) OneKey
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.

"""Protocol V2 wallet sessions: the session object and which wallet to open."""

from __future__ import annotations

import typing as t
import unicodedata
import uuid

from .. import client, exceptions, messages

if t.TYPE_CHECKING:
from .client import OneKeyClientV2


class SessionV2(client.Session["OneKeyClientV2", t.Optional[str]]):
"""Protocol V2 wallet session compatible with `onekeylib.btc` workflows.

Exposes an opaque local correlation ID (`session.id`); raw firmware
session identifiers stay internal to the client.
"""

def __init__(
self,
client: "OneKeyClientV2",
*,
firmware_session_id: bytes | None,
btc_test_address: str | None = None,
attach_pin: bool = False,
root_fingerprint: bytes | None = None,
) -> None:
opaque_id = uuid.uuid4().hex if firmware_session_id is not None else None
super().__init__(client, opaque_id, root_fingerprint=root_fingerprint)
self._firmware_session_id = firmware_session_id
self._btc_test_address = btc_test_address
self.attach_pin = attach_pin

@property
def seedless(self) -> bool:
return self._firmware_session_id is None

@property
def btc_test_address(self) -> str | None:
"""Public identity of the wallet this session opened.

Firmware derives it from the wallet seed, so two sessions with the same
value are the same wallet. It is not an address the wallet uses.
"""
return self._btc_test_address

def close(self) -> None:
self.client._retire_session(self)


def passphrase_request(
passphrase: str | client.PassphraseSetting | None,
status: messages.DeviceStatus,
) -> tuple[messages.DeviceSessionAskPassphrase, float] | None:
"""The passphrase request (and its timeout) that selects the wallet to open.

Returns None when the wallet the unlock selected opens as it is. Raises when
the setting cannot apply to the device's state. `PassphraseSetting.NONE`
opens no wallet and is handled by the caller.
"""
attach_pin = status.unlocked_by_attach_to_pin is True
if passphrase is client.PassphraseSetting.STANDARD_WALLET:
if attach_pin:
raise exceptions.OneKeyException(
"Device is unlocked with Attach PIN; lock and unlock with Main PIN for the standard wallet."
)
if status.passphrase_enabled:
return messages.DeviceSessionAskPassphrase(
passphrase="",
on_device=False,
seed_domains=[1],
), 30.0
elif passphrase is client.PassphraseSetting.ON_DEVICE:
if attach_pin or not status.passphrase_enabled:
raise exceptions.OneKeyException(
"On-device passphrase entry requires Main PIN unlock with passphrase protection enabled."
)
return messages.DeviceSessionAskPassphrase(
on_device=True,
seed_domains=[1],
), 120.0
elif isinstance(passphrase, str):
normalized = unicodedata.normalize("NFKD", passphrase)
if attach_pin:
raise exceptions.OneKeyException(
"Cannot supply a passphrase while unlocked with Attach PIN."
)
if normalized and not status.passphrase_enabled:
raise exceptions.OneKeyException(
"Passphrase protection is disabled on this device."
)
if status.passphrase_enabled:
return messages.DeviceSessionAskPassphrase(
passphrase=normalized,
on_device=False,
seed_domains=[1],
), 30.0
elif passphrase is client.PassphraseSetting.AUTO:
if not attach_pin and status.passphrase_enabled:
return messages.DeviceSessionAskPassphrase(
on_device=True,
seed_domains=[1],
), 120.0
return None


def is_complete(opened: messages.DeviceSession) -> bool:
"""Whether a newly opened session reply names a usable Bitcoin wallet."""
return bool(opened.session_id and opened.btc_test_address and 1 in opened.seed_domains)


def resumes(session: SessionV2, resumed: messages.DeviceSession) -> bool:
"""Whether a resume reply restored exactly the wallet `session` opened."""
return bool(
resumed.session_id
and resumed.session_id == session._firmware_session_id
and resumed.btc_test_address == session._btc_test_address
and 1 in resumed.seed_domains
)
Loading
Loading