-
-
Notifications
You must be signed in to change notification settings - Fork 13
feat: hardware wallet emulators #560
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
montelaidev
wants to merge
31
commits into
main
Choose a base branch
from
feat/speculos-packages
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 15 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
fd40efd
feat: add new hardware entropy type option
montelaidev cd75414
feat: ledger dmk bridge and middleware fix
montelaidev 986bddb
fix: use ble for bridge
montelaidev e434b83
fix: rename bridge and transport to be mobile specific
montelaidev c27079a
fix: remove patch
montelaidev b3e201b
Merge remote-tracking branch 'origin/main' into feat/ledger-dmk-mobile
montelaidev 424c816
chore: add .worktrees/ to .gitignore
montelaidev e80fc5b
feat(speculos): add @metamask/speculos and @metamask/speculos-up pack…
montelaidev 5b74d06
fix(speculos): resolve all ESLint errors across both packages
montelaidev e7361c9
feat: update to hw-emulator
montelaidev aea9751
fix: remove not used
montelaidev 5320a49
fix: retry
montelaidev a73de59
revert: ledger code
montelaidev 50391d0
fix: readme and licence
montelaidev abde647
fix: remove the download ability
montelaidev 8c2a839
fix: update lock
montelaidev e3611c6
chore: add changelog
montelaidev 4bf3baf
fix: lint, add jsdoc and pass env to docker
montelaidev 0c3023d
feat: add speculos up
montelaidev c769de1
fix: address comments
montelaidev c019355
fix: yarn lock
montelaidev e843f55
fix: display env
montelaidev 85a9ca9
fix: changelog and readme
montelaidev 22cfc1a
fix: seed
montelaidev 45eb689
feat: create default binary and scripts to generate binary
montelaidev 8f2d47b
feat: create default binary and scripts to generate binary
montelaidev 9ae4604
fix: test and lint
montelaidev c77d9ee
fix: package name and lint
montelaidev 08e9687
fix: change runner type
montelaidev 0ab7c8c
fix: lint
montelaidev de887b2
fix: lint and have ci only build linux
montelaidev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -77,4 +77,7 @@ node_modules/ | |
| !.yarn/versions | ||
|
|
||
| # Cursor rules | ||
| .cursorrules | ||
| .cursorrules | ||
|
|
||
| # Git worktrees | ||
| .worktrees/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -254,4 +254,4 @@ | |
| "count": 2 | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| MIT License | ||
|
|
||
| Copyright (c) 2026 MetaMask | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| # `@metamask/hw-emulator` | ||
|
|
||
| Hardware wallet emulator lifecycle, transport, and device interaction for E2E testing. | ||
|
|
||
| Provides a programmatic interface for launching and controlling hardware wallet emulators (Ledger via [Speculos](https://github.com/LedgerHQ/speculos)), sending APDU commands, and automating device screen interactions (button presses, touch gestures) — all without physical hardware. | ||
|
|
||
| ## Installation | ||
|
|
||
| `yarn add @metamask/hw-emulator` | ||
|
|
||
| or | ||
|
|
||
| `npm install @metamask/hw-emulator` | ||
|
|
||
| ## Supported Devices | ||
|
|
||
| | Device | Model ID | Interaction Type | | ||
| | --------- | -------- | ---------------- | | ||
| | Nano S+ | `nanosp` | Button | | ||
| | Nano X | `nanox` | Button | | ||
| | Stax | `stax` | Touch | | ||
| | Flex | `flex` | Touch | | ||
|
|
||
| ## Quick Start | ||
|
|
||
| ### Docker Mode (recommended for macOS / CI) | ||
|
|
||
| ```typescript | ||
| import { createEmulator, EmulatorType } from '@metamask/hw-emulator'; | ||
|
|
||
| const emulator = createEmulator(EmulatorType.Ledger, { | ||
| device: 'flex', | ||
| mode: 'docker', | ||
| }); | ||
|
|
||
| await emulator.start(); | ||
| await emulator.approveTransaction(); | ||
| await emulator.stop(); | ||
| ``` | ||
|
|
||
| ### Native Mode (Linux only) | ||
|
|
||
| Requires the Speculos binary to be installed and available on `PATH`, or passed via the `binary` option. | ||
|
|
||
| ```typescript | ||
| import { createEmulator, EmulatorType } from '@metamask/hw-emulator'; | ||
|
|
||
| const emulator = createEmulator(EmulatorType.Ledger, { | ||
| device: 'nanosp', | ||
| mode: 'native', | ||
| binary: '/usr/local/bin/speculos', | ||
| }); | ||
|
|
||
| await emulator.start(); | ||
| await emulator.approveSigning(); | ||
| await emulator.stop(); | ||
| ``` | ||
|
|
||
| ## API | ||
|
|
||
| ### `createEmulator(type, options?)` | ||
|
|
||
| Factory function that creates a `HardwareWalletEmulator` instance. | ||
|
|
||
| - **`type`** — `'ledger'` (via `EmulatorType.Ledger`). Trezor support is not yet implemented. | ||
| - **`options`** — See [`SpeculosOptions`](#speculosoptions). | ||
|
|
||
| ### `HardwareWalletEmulator` | ||
|
|
||
| | Method | Description | | ||
| | ------------------------ | ---------------------------------------- | | ||
| | `start()` | Start the emulator (Docker or native). | | ||
| | `stop()` | Stop the emulator and clean up resources.| | ||
| | `isRunning()` | Returns whether the emulator is active. | | ||
| | `approveTransaction()` | Approve the current transaction on screen.| | ||
| | `approveSigning()` | Approve the current signing request. | | ||
| | `rejectTransaction()` | Reject the current transaction on screen.| | ||
| | `navigateToMainMenu()` | Navigate back to the device main menu. | | ||
| | `getInteraction()` | Get the low-level device interaction API. | | ||
|
|
||
| ### `SpeculosOptions` | ||
|
|
||
| | Option | Type | Default | Description | | ||
| | --------------- | -------- | ----------- | ----------------------------------------------- | | ||
| | `device` | `string` | `'flex'` | Device model ID (`nanosp`, `nanox`, `stax`, `flex`). | | ||
| | `seed` | `string` | Built-in | Mnemonic seed for deterministic accounts. | | ||
| | `apduPort` | `number` | `9998` | APDU communication port. | | ||
| | `apiPort` | `number` | `5001` | Speculos REST API port. | | ||
| | `wsBridgePort` | `number` | `9876` | WebSocket bridge port for WebHID mock. | | ||
| | `mode` | `string` | Auto | Run mode: `'docker'` or `'native'`. Auto-detected. | | ||
| | `binary` | `string` | — | Path to Speculos binary (native mode only). | | ||
| | `display` | `string` | `'headless'`| Display mode. | | ||
| | `loadNvram` | `boolean`| `true` | Load persisted NVRAM state. | | ||
| | `startTimeout` | `number` | `60000` | Startup timeout in ms. | | ||
|
|
||
| ### Low-Level APIs | ||
|
|
||
| The package also exports granular components for advanced use cases: | ||
|
|
||
| - **`SpeculosClient`** — HTTP client for the Speculos REST API (APDU exchange, screen events). | ||
| - **`ApduBridge`** — WebSocket-to-APDU bridge for browser-based WebHID mocking. | ||
| - **`DockerManager`** — Direct Docker Compose lifecycle management. | ||
| - **`createProcessManager()`** — Native Speculos process spawning and monitoring. | ||
| - **`createDeviceInteraction()`** — Screen automation (button presses, touch coordinates). | ||
| - **`withRetry()` / `ExponentialBackoff`** — Resilience utilities for flaky device communication. | ||
| - **`createLedgerHidFramingSession()`** — Low-level Ledger HID frame encoding/decoding. | ||
| - **`getWebHidMockScript()`** — Generates a browser script to mock WebHID for E2E tests. | ||
|
|
||
| ## Docker Setup | ||
|
|
||
| The package includes a `docker-compose.yml` for running Speculos via Docker: | ||
|
|
||
| ```bash | ||
| # Start with default device (Flex) | ||
| docker compose up -d | ||
|
|
||
| # Start with a specific device | ||
| SPECULOS_DEVICE=nanosp docker compose up -d | ||
| ``` | ||
|
|
||
| The ELF app binaries for all supported devices are bundled in the `apps/` directory. | ||
|
|
||
| ## Deterministic Accounts | ||
|
|
||
| The default seed produces these pre-funded Ethereum accounts: | ||
|
|
||
| | Index | Address | | ||
| | ----- | ------------------------------------------------ | | ||
| | 0 | `0x24fC293546A31F5Ce73bAfecE37969A95CCd1aBf` | | ||
| | 1 | `0x730A5c73bC3ACcf56daba2D5D897bEb10F852865` | | ||
| | 2 | `0x805c2797CCBa57887F5fA0DD95C017145d67604a` | | ||
| | 3 | `0x2Bf9972F600D8C3B3f0AEe8f1e17Fc4631242fF4` | | ||
| | 4 | `0xDc660e6D52F6f774d0879f99929711155Bc03902` | | ||
|
|
||
| ## Contributing | ||
|
|
||
| This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/accounts#readme). |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| version: '3.8' | ||
| services: | ||
| speculos: | ||
| image: ghcr.io/ledgerhq/speculos:latest | ||
| container_name: metamask-speculos | ||
| ports: | ||
| - '9998:9999' | ||
| - '5001:5000' | ||
| volumes: | ||
| - ./apps:/speculos/apps | ||
| - ./nvram/main_nvram.bin:/speculos/main_nvram.bin | ||
| environment: | ||
| - DISPLAY=:99 | ||
| command: > | ||
| --model ${SPECULOS_DEVICE:-nanosp} | ||
| /speculos/apps/${SPECULOS_ELF_FILENAME:-ethereum-nanosp.elf} | ||
| --seed "urban secret spare tunnel rubber rally ladder spatial feature elite success" | ||
|
cursor[bot] marked this conversation as resolved.
Outdated
|
||
| --display headless | ||
|
cursor[bot] marked this conversation as resolved.
Outdated
|
||
| --apdu-port 9999 | ||
| --api-port 5000 | ||
| --load-nvram | ||
| healthcheck: | ||
| test: | ||
| - CMD-SHELL | ||
| - python3 -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/')" | ||
| interval: 2s | ||
| timeout: 3s | ||
| retries: 10 | ||
|
|
||
| --- | ||
| # Note: | ||
| # - APDU port mapped from host 9998 to container 9999 (9999 is used by PhishingWarningPageServer) | ||
| # - REST API mapped from host 5001 to container 5000 (5000 used by macOS Control Center) | ||
| # - SPECULOS_DEVICE selects the device model (nanosp, nanox, stax, flex) | ||
| # - SPECULOS_ELF_FILENAME is the ELF filename inside /speculos/apps/ (NOT the host path) | ||
| # - Defaults to Nano S+ (nanosp) for local development without SPECULOS_DEVICE set | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| const merge = require('deepmerge'); | ||
| const path = require('path'); | ||
| const baseConfig = require('../../jest.config.packages'); | ||
|
|
||
| module.exports = merge(baseConfig, { | ||
| displayName: path.basename(__dirname), | ||
| coverageThreshold: { global: { branches: 10, functions: 20, lines: 20, statements: 20 } }, | ||
| }); |
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| { | ||
| "name": "@metamask/hw-emulator", | ||
| "version": "0.1.0", | ||
| "description": "Hardware wallet emulator lifecycle, transport, and device interaction for E2E testing", | ||
| "keywords": [ | ||
| "hardware-wallet", | ||
| "emulator", | ||
| "ledger", | ||
| "trezor", | ||
| "e2e", | ||
| "testing", | ||
| "metamask" | ||
| ], | ||
| "homepage": "https://github.com/MetaMask/accounts/tree/main/packages/hw-emulator#readme", | ||
| "bugs": { | ||
| "url": "https://github.com/MetaMask/accounts/issues" | ||
| }, | ||
| "license": "MIT", | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "https://github.com/MetaMask/accounts.git" | ||
| }, | ||
| "files": [ | ||
| "dist/", | ||
| "apps/", | ||
| "nvram/", | ||
| "docker-compose.yml" | ||
| ], | ||
| "sideEffects": false, | ||
| "main": "./dist/index.cjs", | ||
| "types": "./dist/index.d.cts", | ||
| "exports": { | ||
| ".": { | ||
| "import": { | ||
| "types": "./dist/index.d.mts", | ||
| "default": "./dist/index.mjs" | ||
| }, | ||
| "require": { | ||
| "types": "./dist/index.d.cts", | ||
| "default": "./dist/index.cjs" | ||
| } | ||
| }, | ||
| "./package.json": "./package.json" | ||
| }, | ||
| "publishConfig": { | ||
| "access": "public", | ||
| "registry": "https://registry.npmjs.org/" | ||
| }, | ||
| "scripts": { | ||
| "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", | ||
| "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", | ||
| "build:clean": "yarn build --clean", | ||
| "build:docs": "typedoc", | ||
| "changelog:update": "../../scripts/update-changelog.sh @metamask/hw-emulator", | ||
| "changelog:validate": "../../scripts/validate-changelog.sh @metamask/hw-emulator", | ||
| "publish:preview": "yarn npm publish --tag preview", | ||
| "since-latest-release": "../../scripts/since-latest-release.sh", | ||
| "test": "yarn test:source && yarn test:types", | ||
| "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache", | ||
| "test:source": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter", | ||
| "test:types": "../../scripts/tsd-test.sh ./src", | ||
| "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose", | ||
| "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" | ||
| }, | ||
| "dependencies": { | ||
| "@ledgerhq/devices": "^7.0.0", | ||
| "ws": "^8.18.0" | ||
| }, | ||
| "devDependencies": { | ||
| "@lavamoat/allow-scripts": "^3.2.1", | ||
| "@lavamoat/preinstall-always-fail": "^2.1.0", | ||
| "@metamask/auto-changelog": "^6.1.0", | ||
| "@ts-bridge/cli": "^0.6.3", | ||
| "@types/jest": "^29.5.12", | ||
| "@types/node": "^20.12.12", | ||
| "@types/ws": "^8.18.1", | ||
| "depcheck": "^1.4.7", | ||
| "jest": "^29.5.0", | ||
| "jest-it-up": "^3.1.0", | ||
| "rimraf": "^5.0.7", | ||
| "ts-jest": "^29.0.5", | ||
| "ts-node": "^10.9.2", | ||
| "tsd": "^0.31.0", | ||
| "typedoc": "^0.25.13", | ||
| "typescript": "~5.3.3" | ||
| }, | ||
| "engines": { | ||
| "node": "^18.18 || >=20" | ||
| }, | ||
| "lavamoat": { | ||
| "allowScripts": { | ||
| "@lavamoat/preinstall-always-fail": false | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { createEmulator } from './factory'; | ||
| import { EmulatorType } from './types'; | ||
| import type { EmulatorType as EmulatorTypeValue } from './types'; | ||
|
|
||
| describe('createEmulator', () => { | ||
| it('creates a Ledger emulator', () => { | ||
| const emu = createEmulator(EmulatorType.Ledger); | ||
| expect(emu).toBeDefined(); | ||
| expect(emu.isRunning()).toBe(false); | ||
| }); | ||
|
|
||
| it('creates a Ledger emulator with options', () => { | ||
| const emu = createEmulator(EmulatorType.Ledger, { device: 'nanosp' }); | ||
| expect(emu).toBeDefined(); | ||
| expect(emu.isRunning()).toBe(false); | ||
| }); | ||
|
|
||
| it('creates a Ledger emulator from an EmulatorType value', () => { | ||
| const type: EmulatorTypeValue = EmulatorType.Ledger; | ||
|
|
||
| const emu = createEmulator(type); | ||
|
|
||
| expect(emu).toBeDefined(); | ||
| expect(emu.isRunning()).toBe(false); | ||
| }); | ||
|
|
||
| it('throws for trezor (not yet implemented)', () => { | ||
| expect(() => createEmulator(EmulatorType.Trezor)).toThrow( | ||
| 'Trezor emulator is not yet implemented', | ||
| ); | ||
| }); | ||
|
|
||
| it('throws for unknown emulator type', () => { | ||
| expect(() => | ||
| createEmulator('unknown' as typeof EmulatorType.Ledger), | ||
| ).toThrow('Unknown emulator type'); | ||
| }); | ||
|
|
||
| it('returns an emulator with the HardwareWalletEmulator interface', () => { | ||
| const emu = createEmulator(EmulatorType.Ledger); | ||
| expect(typeof emu.start).toBe('function'); | ||
| expect(typeof emu.stop).toBe('function'); | ||
| expect(typeof emu.isRunning).toBe('function'); | ||
| expect(typeof emu.getInteraction).toBe('function'); | ||
| expect(typeof emu.approveTransaction).toBe('function'); | ||
| expect(typeof emu.approveSigning).toBe('function'); | ||
| expect(typeof emu.rejectTransaction).toBe('function'); | ||
| expect(typeof emu.navigateToMainMenu).toBe('function'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.