Skip to content

feat(onekeylib): add standalone Python library for OneKey V1 and V2 devices - #1003

Open
wabicai wants to merge 20 commits into
onekeyfrom
feat/onekeylib-python
Open

wabicai wants to merge 20 commits into
onekeyfrom
feat/onekeylib-python

Conversation

@wabicai

@wabicai wabicai commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds a standalone Python library in packages/onekeylib/ for planned distribution on PyPI. It is based on a trimmed-down version of trezorlib 0.20.2, retains the LGPL-3.0 licensing materials, and supports both legacy OneKey devices (Protocol V1) and Pro 2 / Neo (Protocol V2).

Changes

  • Minimal runtime dependencies: Keep only libusb1 and typing_extensions. Remove support for non-Bitcoin chains, THP, Bridge, BLE, the CLI, and Trezor-specific firmware logic. Reduce messages.py from 10,076 lines to 1,991.

  • Unified device support:

    • Protocol V1 (Classic / Classic 1S / Mini / Touch / Pro) uses WebUsbTransport and protocol_v1.
    • Protocol V2 (Pro 2 / Neo, 1209:4f4c) uses ProtoLinkTransport (USB bulk transfers with 0x5A/CRC8 framing) and protocol_v2 (main PIN and Attach PIN via PIN_ANY, passphrases, session validation, and on-device cancellation without disconnecting).
    • Both protocols share the public onekeylib.client and onekeylib.btc APIs, which include get_public_node, get_address, sign_tx, and sign_message.
  • Branding and licensing: Retain the LGPL-3.0 COPYING file and source attribution and copyright notices in file headers. Use OneKey naming consistently in identifiers, exceptions, environment variables, error messages, and links.

  • Host API for wallet selection (Protocol V2): device_status(), ask_pin(pin_type), lock(), get_current_session(), SessionV2.btc_test_address and ble_name, so a host such as Electrum can choose, check and relock a wallet without private attributes. The README section "Choosing and checking a wallet (Protocol V2)" describes them.

  • Host cancellation: client.cancel_check lets a host abandon a pending read. If the device may be showing a prompt, onekeylib sends Cancel (also instead of ButtonAck) and then closes the link. Undecodable replies raise ProtocolError.

  • Device detection: get_default_client skips V1 devices that are not OneKey, and Features reads the 5xx/6xx OneKey fields.

  • Protocol V2 package layout: onekeylib.protocol_v2 is a package split by responsibility, with no behavior change: client (OneKeyClientV2), link (encoding and link negotiation), requests (request classes), failures (failure replies to exceptions), sessions (SessionV2 and the passphrase request for each setting) and workflow (the signing reservation). from onekeylib.protocol_v2 import OneKeyClientV2, SessionV2 still works.

  • Release workflow: .github/workflows/onekeylib.yml tests and builds on pull requests that touch the package. Releases follow the npm flow (package-publish.yml): run the workflow by hand and choose pypi or testpypi. It reads the version from pyproject.toml, checks it against __version__, tests, builds and publishes with Trusted Publishing (environments pypi and testpypi), so no token is stored. A stable PyPI release then gets the tag onekeylib-v<version> and a GitHub release with the wheel and sdist, not marked as the repository's latest release. PEP 440 prereleases are published without a tag or release.

Verification

  • pytest tests -q: 69 passed.
  • flake8 --select=E9,F63,F7,F82,F401,F811 src tests: passed.
  • python -m build and twine check --strict dist/*: passed.
  • actionlint on the workflow: passed. The publish, tag and release steps run for the first time on the first release.
  • node scripts/check-versions.js: passed. Existing JavaScript workspace packages are unaffected.
  • The Electrum OneKey plugin (spesmilo/electrum#11161) now runs on this library; its 164 tests pass against it.
  • Not yet tested on a physical device.

This PR can be reviewed independently of the standalone Electrum ZIP plugin PR #998, which can be merged first.


Devin Review

@socket-security

socket-security Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedpypi/​setuptools@​84.2.17410010010070
Addedpypi/​typing-extensions@​4.16.0100100100100100

View full report

@sidmorizon

Copy link
Copy Markdown
Contributor

@codex review

@sidmorizon

Copy link
Copy Markdown
Contributor

@codex security review

@sidmorizon

Copy link
Copy Markdown
Contributor

Cursor review failed.

Remote error: cursor_permission_denied: HTTP 403 Forbidden: Cloud Agent is not available for free users. Please upgrade to Pro.

@cursor

cursor Bot commented Nov 25, 2026

Copy link
Copy Markdown

Skipping Bugbot: Bugbot is disabled for this repository. Visit the Bugbot dashboard to update your settings.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T06:42:38.905854Z 1de4f32 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 16 potential issues.

3 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment thread packages/onekeylib/src/onekeylib/btc.py Resolved
Comment thread packages/onekeylib/src/onekeylib/log.py Resolved
@sidmorizon

Copy link
Copy Markdown
Contributor

Devin Cloud review ↗

@sidmorizon

Copy link
Copy Markdown
Contributor

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1de4f32f42

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/onekeylib/src/onekeylib/log.py Resolved
Comment thread packages/onekeylib/src/onekeylib/btc.py Resolved
Comment thread packages/onekeylib/src/onekeylib/btc.py Resolved
Comment thread packages/onekeylib/src/onekeylib/btc.py Resolved
Comment thread packages/onekeylib/src/onekeylib/btc.py Resolved
Comment thread packages/onekeylib/src/onekeylib/btc.py Resolved
Comment thread .github/workflows/onekeylib.yml Resolved
VERSION: ${{ steps.version-info.outputs.version }}
IS_PRERELEASE: ${{ steps.version-info.outputs.is_prerelease }}
run: |
if [ "$GITHUB_REF" != "refs/heads/onekey" ]; then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1: [Identify the production PyPI branch restriction]

The earlier comment at .github/workflows/onekeylib.yml:67 covered tag-triggered publishing. The manual path now checks for refs/heads/onekey at .github/workflows/onekeylib.yml:80. GitHub loads that check from the selected ref, and the workflow says the pypi environment has no separate approval. If that environment also permits other refs, a contributor who can write and dispatch a branch can publish an unreviewed build that users install as the official SDK.

The environment’s deployment branch policy, or an equivalent control enforced independently of the selected workflow, would settle whether only refs/heads/onekey can request production publishing credentials. No code change is requested until that policy is known. Please reply in this thread with the policy or equivalent control.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The selected ref supplies the workflow that checks GITHUB_REF. Please provide the production pypi environment’s deployment branch policy or an equivalent independently enforced control showing that only refs/heads/onekey can obtain production publishing credentials.

Comment thread .github/workflows/onekeylib.yml Resolved
Comment thread .github/workflows/onekeylib.yml Resolved
Comment thread .github/workflows/onekeylib.yml Resolved
Record the build's wheel and sdist with their SHA-256 before the upload, so
the attestation files the publish action writes into dist/ are not taken
for packages. Before uploading, every file the index already lists for this
version must be one of them with the same digest; otherwise nothing is
uploaded, so a re-run can only complete the same build and two builds are
never mixed under one version. The final check compares the index with the
recorded list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Session.close() passed the session object as a log argument, so a handler
that exports record arguments could receive a V1 session and its firmware
session ID. Pass the local tag instead, as the other session logs do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread .github/workflows/onekeylib.yml Resolved
wabicai and others added 2 commits December 3, 2026 11:15
Move only: the module becomes protocol_v2/client.py with parent-relative
imports, and protocol_v2/__init__.py re-exports OneKeyClientV2, SessionV2
and REQUIRED_V2_MESSAGES, so `from onekeylib.protocol_v2 import ...` keeps
working. Keeping the move apart from the split lets `git log --follow`
trace the client's history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No behavior change. OneKeyClientV2 keeps every public method and the order
of every request it sends; its parts move into modules of their own:

- link: message encoding over proto_link, the negotiated link state
  (LinkState) and the ProtocolInfo check.
- requests: which requests are mid-workflow, seedless, interactive, and so on.
- failures: failure replies to exceptions (failure_error).
- sessions: SessionV2, the passphrase request each PassphraseSetting sends,
  and the checks on DeviceSession replies.
- workflow: the signing exchange a session keeps reserved
  (WorkflowReservation), formerly three client attributes.

The tests reach the reservation as client._workflow.session/.token instead
of the old attributes; their assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…blishing

Session.close() logs only the exception type when EndSession fails:
InvalidSessionError keeps the reply, which may carry the firmware session ID.

The publish job runs one at a time per index, so two runs of the same
version cannot both pass the preflight and mix their files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread .github/workflows/onekeylib.yml Resolved
@wabicai

wabicai commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the two remaining P1 workflow findings in 37458e3e2:

  1. Queued publish runs (#4781759698): Added queue: max alongside cancel-in-progress: false on concurrency: onekeylib-publish-${{ inputs.repository }} so multiple pending releases for the same index queue sequentially without canceling each other.
  2. Atomic per-index/version build manifest reservation (#4779400853 / #4781518445): Before uploading either file to PyPI or TestPyPI, publish now rejects any unexpected files in dist/ and atomically reserves a durable Git ref refs/onekeylib-manifests/<index>/<normalized_version> (via POST /git/tags + POST /git/refs, create-if-not-exists) containing the canonical {filename: sha256} manifest. The ref persists across failed jobs and does not rely on PyPI/TestPyPI JSON API consistency, so a conflicting build is blocked even after a partial failed upload while retries of the exact reserved build match and proceed.

Comment thread .github/workflows/onekeylib.yml Resolved
Comment thread .github/workflows/onekeylib.yml Resolved
Comment thread .github/workflows/onekeylib.yml Outdated
exit 1
fi
# PEP 440 canonical version and prerelease flag (a, b, rc, dev).
NORMALIZED_VERSION=$(python -c "import sys; from packaging.version import Version; print(Version(sys.argv[1]))" "$VERSION")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1: Equivalent versions bypass build reservations

Severity: severe

For 0.1 and 0.1.0, NORMALIZED_VERSION produces separate reservations for the same PyPI release. If preflight misses a partial upload, the second build can add different files to that release.

Suggested fix:

          NORMALIZED_VERSION=$(python -c "import sys; from packaging.utils import canonicalize_version; print(canonicalize_version(sys.argv[1]))" "$VERSION")

Comment on lines +268 to +273
if not isinstance(reserved, dict) or reserved != manifest:
sys.exit(
f"❌ {index_name} {norm_version} is already reserved for a different build: "
f"reserved={sorted(reserved.items()) if isinstance(reserved, dict) else reserved} "
f"vs local={sorted(manifest.items())}"
)

@sidmorizon sidmorizon Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1: Artifact expiry strands unpublished releases

Severity: severe

If publishing stops before any upload and the build artifact expires, a fresh run cannot reproduce the reserved sdist. The reserved != manifest check blocks publishing that version even though the index is empty.

Originally reported at .github/workflows/onekeylib.yml:268-273 on commit 37458e3e29378e5c5fe3e8b321226f7ff2804c3b. The finding's code and surrounding context were verified unchanged at commit 38f84d8f572d6b7a2e74865fa99c7c23eb76386d; other code may have changed since the review.

@huhuanming huhuanming left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code review findings (excluding hardware verification, and omitting workflow P1 items already tracked in existing threads such as contents: write job isolation, equivalent version normalization, artifact expiry deadlock, and pypi environment branch policy).

return resp.message or ""

@enter_context
def refresh_features(self) -> messages.Features:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Medium] Missing _check_no_workflow() guard on management helpers

device_status(), ask_pin(), lock(), get_current_session(), and get_session() all call self._check_no_workflow() to prevent interleaving requests during an active SignTx/TxAck workflow. However, ping() (L226), refresh_features() (L246), ble_name (L300, which calls refresh_features()), and ensure_unlocked() (L380) do not.

If a host reads ble_name or refreshes features while a signing exchange is reserved, management requests will be sent mid-workflow and can desync the device signing state.


self._features = messages.Features(
vendor="onekey.so",
major_version=info.protocol_version,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Medium] client.version on V2 always reports (1, 0, 0)

major_version is populated from info.protocol_version (1) with minor_version=0, patch_version=0, so client.version reflects the protocol version rather than the firmware version. If hosts (e.g., Electrum) inspect client.version for firmware capability checks, this may be misleading—either populate the actual firmware version if available from DeviceInfo or document this limitation clearly.

# Only the exchange this Cancel interrupts is released; a new one started
# after the Cancel was sent keeps its reservation.
token = self._workflow.token
if self.transport.is_open():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Medium] Unsynchronized check-then-act race in cancel()

cancel() checks self.transport.is_open() and calls self._raw_write(messages.Cancel()) and self._end_workflow(token) without synchronization against concurrent link closure or workflow transitions. If the active request thread closes the transport between is_open() and _raw_write(), cancel() raises TransportException instead of handling a closed link cleanly.

if res.serialized.signature_index is not None:
idx = res.serialized.signature_index
sig = res.serialized.signature
if signatures[idx] is not None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Low] Validate signature_index bounds before indexing signatures

signatures[idx] does not check 0 <= idx < len(inputs). If a buggy/unexpected reply returns a negative signature_index, Python's negative indexing would silently write to the end of signatures instead of raising an error.

OUTDATED_FIRMWARE_ERROR = """
Your OneKey firmware is out of date. Update it with the following command:
onekeyctl firmware update
Or visit https://suite.onekey.io/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Low] Stale CLI command and URL in OUTDATED_FIRMWARE_ERROR

This package removes the CLI (so onekeyctl firmware update does not exist), and https://suite.onekey.io/ appears to be a leftover from replacing suite.trezor.io rather than an official OneKey domain (e.g. https://onekey.so/).

#
# Copyright (C) SatoshiLabs and contributors
# Modifications Copyright (C) OneKey
# Modifications Copyright (C) OneKey

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Nit] Duplicate copyright header line

# Modifications Copyright (C) OneKey is duplicated here (and in packages/onekeylib/src/onekeylib/models.py:4-5).

Comment thread .github/workflows/onekeylib.yml Outdated
# part-way: files the index already has from this build are skipped.
- name: Publish to PyPI
if: inputs.repository == 'pypi'
uses: pypa/gh-action-pypi-publish@release/v1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Medium] Pin third-party Actions to full commit SHAs

pypa/gh-action-pypi-publish@release/v1 (and the other external actions in this workflow) are pinned to mutable branch/major tags rather than full commit SHAs. On a PyPI OIDC publish job with id-token: write, pinning to immutable commit SHAs is recommended for supply-chain hardening.

zy2000-star
zy2000-star previously approved these changes Dec 4, 2026
@wabicai

wabicai commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all remaining P1 workflow findings and @huhuanming review comments in 38f84d8f5:

Workflow (.github/workflows/onekeylib.yml)

  • Separate contents: write from id-token: write (#4786910769): Moved Git manifest reservation into a dedicated reserve job (permissions: contents: write). The publish job now has only id-token: write, depends on reserve, and re-verifies dist/ SHA-256 digests against needs.reserve.outputs.manifest before calling pypa/gh-action-pypi-publish.
  • Canonical PEP 440 version (#4786911719 / #4787231200): Confirmed PyPI/Warehouse treats equivalent PEP 440 spellings (e.g., 0.1 and 0.1.0) as the same release. NORMALIZED_VERSION now uses packaging.utils.canonicalize_version(...) so equivalent spellings share one reservation ref.
  • Reproducible sdist & wheel builds (#4787234167): test-and-build now exports SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) and normalizes .tar.gz tar/gzip metadata deterministically before twine check, so a fresh run on the same commit reproduces the exact reserved SHA-256 digests even after build artifacts expire.
  • Pin third-party Actions (#4787621307): Pinned all 9 uses: references (actions/checkout, actions/setup-python, actions/upload-artifact, actions/download-artifact, pypa/gh-action-pypi-publish) to full 40-char commit SHAs.

Python SDK (packages/onekeylib)

  • Workflow guards (#4787621204): Added _check_no_workflow() to ping(), refresh_features() (also guarding ble_name), and ensure_unlocked().
  • V2 firmware version (#4787621223): Added DeviceMainMcuInfo / DeviceFirmwareImageInfo fields to DeviceInfo, requested main_mcu=True + version=True, and populated Features.{major,minor,patch}_version from main_mcu.application.version (falling back to (protocol_version, 0, 0) only when omitted).
  • Thread-safe cancel() (#4787621235): Synchronized WorkflowReservation transitions with a lock, acquired self._lock non-blockingly when idle, and handled concurrent transport closure cleanly without raising TransportException.
  • signature_index bounds check (#4787621253): Validated 0 <= idx < len(signatures) in btc.sign_tx() before indexing.
  • Cleanup (#4787621275 / #4787621297): Updated OUTDATED_FIRMWARE_ERROR to remove stale onekeyctl / suite.onekey.io references and removed duplicate copyright lines in __init__.py, models.py, and messages.py.
  • Tests: Added 5 unit tests (75 passed, 20 subtests passed, flake8 clean).

Comment on lines +644 to +649
except TransportException:
# If the active thread closed the link concurrently between
# is_open() and _raw_write(), the device already dropped the
# exchange; treat that as cleanly cancelled.
if self.transport.is_open():
raise

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 P1: Silent failure to send Cancel

Severity: severe

When a USB write times out or is incomplete, cancel() returns normally without confirming that it sent Cancel. write_chunk closes the link on write failure, so the closed link masks the error.

@wabicai

wabicai commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Fixed P1 #4797324291 (Silent failure to send Cancel) in 18417a1cb:

  • Added TransportClosed(TransportException) in transport/__init__.py for I/O attempted when handle is None (transport already closed before the write started).
  • Changed ProtoLinkTransport._write_lock to threading.RLock() and acquired it in _close() so link teardown and write_message()/write_chunk() are mutually exclusive.
  • Real USB write timeouts, I/O errors, and short writes continue to close the link and raise TransportException (not TransportClosed).
  • OneKeyClientV2.cancel() now catches only TransportClosed (concurrent close before write) and propagates real TransportException write failures to the caller.
  • Added unit tests covering both TransportClosed and USB write failure/timeout propagation (77 passed, 20 subtests passed, flake8 clean).

@limichange
limichange enabled auto-merge (squash) December 4, 2026 14:02

This branch has not been deployed

No deployments
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.

6 participants