From 810869fc5e5cf7d61766dbfabadebd357d272143 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Thu, 8 Oct 2026 17:36:56 +0530 Subject: [PATCH 01/31] docs(preview): establish parallel recoverable wallet test stream and server hold --- docs/preview/recoverable-wallet/README.md | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 docs/preview/recoverable-wallet/README.md diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md new file mode 100644 index 000000000..facecff72 --- /dev/null +++ b/docs/preview/recoverable-wallet/README.md @@ -0,0 +1,55 @@ +# Recoverable Wallet — parallel Keeper preview + +Status: **parallel development stream, planning and isolated preview setup**. Not a released feature, not a security-reviewed wallet, and not an OpenSpec implementation package. Public name is undecided ("Recoverable Wallet" is a working term). + +## Owner decision (8 October 2026) + +Develop a Bitkey-like Recoverable Wallet **in parallel with** the existing R01–R10 work buckets. This stream is **not** a new R11/R12 bucket, and its feature is **not committed to ship in R9/R10**. User-visible progress must be measured by independently installable, manually testable preview builds, not just code review. No existing release is delayed or silently rescoped to fit this feature. + +**Strict hold: do not change Keeper SigningServer, Relay, production infrastructure, or any server-side recovery interface as part of this preview stream while waiting for Adam's proposed contribution and subsequent owner decision.** The server-side hold is specific to this feature; it does not overturn explicitly approved routine R04/backend maintenance. Any server interaction required by early UI previews must use mocks/disposable isolated test infrastructure, and cannot be represented as validated cryptographic recovery. + +Adam's contribution is welcome, optional, independently reviewed, and must not block client UX, preview packaging, hardware UI, cloud-transport research, test fixtures or safety tests. Do not merge Bitme's exact Hardware+Server-immediate/other-pairs-delayed descriptor into Keeper. Any eventual code use must retain the appropriate MIT notice and follow Keeper review. + +## Non-negotiable product model + +- One Wallet within Keeper; not a replacement for whole-app recovery with the twelve-word **Recovery Key**. +- Standard base **2-of-3 Mobile Key + user-selected Hardware Key + Server Key**. Mobile/Server status is presented automatically; no manual quorum builder. +- Hardware added last among the base keys, using appropriate physical connection, QR or NFC flow. +- Optional Inheritance Key is chosen before final wallet-policy approval. The *final complete* policy is confirmed once; don't fund/register an intermediate wallet. +- Plain base 2-of-3 is not Bitme's timelocked Miniscript descriptor. When inheritance is added, use Keeper's Miniscript policy with compatibility testing for **all** signers. Signing-only hardware (TAPSIGNER/Satochip) is distinct from policy-verifying hardware. +- After inheritance eligibility, independent heir's Inheritance Key + any eligible original signer can form the required 2-of-4 quorum; Keeper server cannot become mandatory for the heir's exit path. +- Cloud encrypted Mobile Key backup in user's iCloud / Google Drive is separate from existing Personal Cloud Backup. Its "healthy" status must be based on cryptographic read-back, not request success. +- Hardware-authorised unlocking via server-held recovery material is an accepted trade-off; design, isolation, replay protection and threat model require independent security review before real funds. +- Contact-based recovery must ultimately be **independent of Keeper's server** if an enrolled contact + accessible encrypted cloud backup are available. +- Hardware + Server supports delayed replacement of missing Mobile Key when cloud backup is missing, once server implementation is allowed. +- Mobile + Hardware and descriptor support server-independent spending/exit. Test actual external-wallet compatibility; public descriptors do not contain private keys. +- Key changes mean new wallet policy and on-chain transfer with fee and original-wallet authorization. Archive the complete predecessor and monitor retained archived addresses indefinitely, including zero-balance wallets. Do not archive merely because the same Mobile Key was restored. +- Keep Recovery Contact distinct from signing keys and Inheritance Key. The existing 12-word Recovery Key is an **additional whole-app recovery route**, not a mandatory prerequisite for this wallet's recovery methods. + +## How the owner will test it + +Deliver a **separate-installation iOS and Android Keeper Preview** (different app identity and storage namespace from production Keeper), testnet-only and isolated from real iCloud/Google Drive backups. Verify the necessary app IDs, native entitlements, cloud containers and distribution access before promising TestFlight or Android APK builds. Keep normal Keeper installed and unaffected. Preview actions may initially be mocked: they must be unmistakably identified as simulated; no fake success, funding or cryptographic-security claims. + +A new preview checkpoint is complete **only after an installable build and a short device-specific owner test checklist are available**, and after actual tests are recorded: + +1. **Prototype/UI**: tap through Add Wallet → recoverable wallet, hardware picker/connection, automatic Mobile/Server status, optional inheritance, one final policy review; include errors/cancel/resume. +2. **Disposable real wallet**: create fixed 2-of-3 wallet on testnet using supported available signers, safely receive/send test sats, inspect proper fees and outputs. No mainnet, no production credentials. +3. **Backup**: encrypted Mobile Key recovery blob, versioning, iCloud/Drive isolation, read-back verification, retry/offline/background/interrupted write tests; retain existing Keeper backup compatibility. +4. **Recovery via hardware**: lose/reinstall disposable preview, prove hardware possession, restore same wallet and explain retain-versus-rotate Mobile Key after restoration. This requires reviewed server protocol; do not simulate as if implemented. +5. **Recovery Contact**: enroll second person/device, approve/decline, backup/reinstall contact credential; recover when Keeper server is demonstrably unreachable. Actual independent channel/crypto is required for completion. +6. **Lost-key, inheritance and exit**: delay/veto/replacement, migration/archive/old deposit, Miniscript policy registration and exact signer paths, descriptor export plus actual compatible external-wallet sweep, with Keeper server offline. +7. **Hardening and mainnet-readiness**: comprehensive adversarial/destructive tests; iOS/Android real NFC/QR hardware and app life-cycle, independent crypto/security review, full regression against then-current Keeper build. Mainnet activation and campaign only after explicit user approval. + +Each checkpoint may be smaller than the grouping above to keep visible feedback frequent. Keep a clean recorded matrix of **simulated / automated / native / physical / security-reviewed / user-tested**, never conflating these. + +## Integration and communications + +- Stay rebased on the current Keeper app branch; keep product-facing changes isolated behind a guarded preview feature path. Nothing is merged into shipping app without reviewed CI/native regression and owner approval. +- Server code is **frozen for this feature pending Adam's contribution and a new owner instruction**. The absence of Adam's PR does not block preview UI, local hardware functionality, cloud transport tests, threat modeling or design. +- Keep existing R5–R10 commitments intact. This work is recorded in a separate **Now — Parallel Recoverable Wallet** tracker entry, *not* a new numbered work bucket. Release integration will be scheduled later on evidence of readiness. +- Prepare, but do not publish, direct factual Bitkey comparison, blog, feature page, demo video, Ask Keeper help, X/Telegram campaign. Emphasize third-party hardware freedom and Miniscript inheritance. Bitkey already publishes source; do not claim otherwise. Keeper owner controls external communications. +- Self-hosted packaging/custom-server settings remain **Later**. No performance/security superiority claims without data. + +## Immediate next action + +Build the separate app-flavor / package identity and local navigable testnet preview **without touching any server repository or production recovery service**. Validate installs alongside production Keeper and separate cloud storage before testing on a real device. Do not represent this README or branch alone as an installable or functional preview. From 034ace55a1cc4c6b3f2f01c1624b1cb8979b608f Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 18:13:04 +0530 Subject: [PATCH 02/31] Add isolated recoverable wallet client preview --- .env.recoverable-preview | 9 + .gitignore | 3 +- App.tsx | 93 +-- ProductionApp.tsx | 71 +++ android/app/build.gradle | 44 +- android/app/src/debug/AndroidManifest.xml | 9 - .../app/src/development/AndroidManifest.xml | 20 + android/app/src/main/AndroidManifest.xml | 15 - .../java/com/hexa_keeper/MainApplication.kt | 5 +- .../app/src/production/AndroidManifest.xml | 20 + .../recoverablePreview/AndroidManifest.xml | 18 + .../recoverablePreview/google-services.json | 22 + .../recoverablePreview/res/values/strings.xml | 5 + docs/preview/recoverable-wallet/README.md | 22 +- .../recoverable-wallet/native-preview.md | 44 ++ index.js | 12 +- ios/Podfile | 5 + ios/hexa_keeper.xcodeproj/project.pbxproj | 441 ++++++++++++++ .../hexa_keeper_recoverable_preview.xcscheme | 78 +++ ios/hexa_keeper/AppDelegate.mm | 4 +- ...hexa_keeper_recoverable_preview-Info.plist | 109 ++++ ...xa_keeper_recoverable_preview.entitlements | 5 + package.json | 4 + .../RecoverableWalletPreviewApp.tsx | 547 ++++++++++++++++++ src/preview/recoverable-wallet/previewFlow.ts | 91 +++ .../recoverable-wallet/previewRuntime.ts | 21 + tests/preview/previewAppBoundary.test.tsx | 58 ++ .../preview/recoverableWalletPreview.test.ts | 85 +++ .../preview/recoverableWalletScreen.test.tsx | 72 +++ 29 files changed, 1834 insertions(+), 98 deletions(-) create mode 100644 .env.recoverable-preview create mode 100644 ProductionApp.tsx create mode 100644 android/app/src/development/AndroidManifest.xml create mode 100644 android/app/src/production/AndroidManifest.xml create mode 100644 android/app/src/recoverablePreview/AndroidManifest.xml create mode 100644 android/app/src/recoverablePreview/google-services.json create mode 100644 android/app/src/recoverablePreview/res/values/strings.xml create mode 100644 docs/preview/recoverable-wallet/native-preview.md create mode 100644 ios/hexa_keeper.xcodeproj/xcshareddata/xcschemes/hexa_keeper_recoverable_preview.xcscheme create mode 100644 ios/hexa_keeper_recoverable_preview-Info.plist create mode 100644 ios/hexa_keeper_recoverable_preview.entitlements create mode 100644 src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx create mode 100644 src/preview/recoverable-wallet/previewFlow.ts create mode 100644 src/preview/recoverable-wallet/previewRuntime.ts create mode 100644 tests/preview/previewAppBoundary.test.tsx create mode 100644 tests/preview/recoverableWalletPreview.test.ts create mode 100644 tests/preview/recoverableWalletScreen.test.tsx diff --git a/.env.recoverable-preview b/.env.recoverable-preview new file mode 100644 index 000000000..5cc8b4fe4 --- /dev/null +++ b/.env.recoverable-preview @@ -0,0 +1,9 @@ +# This file is intentionally public and contains no signing or cloud credentials. +KEEPER_PREVIEW=true +KEEPER_PREVIEW_TESTNET_ONLY=true +ENVIRONMENT=DEVELOPMENT +# Fail closed if a regular service client is accidentally reached by the preview shell. +RELAY=http://127.0.0.1:1/ +SIGNING_SERVER_TESTNET=http://127.0.0.1:1/ +SIGNING_SERVER_MAINNET=http://127.0.0.1:1/ +CHANNEL_URL=http://127.0.0.1:1/ diff --git a/.gitignore b/.gitignore index 8c156fac7..5e8a48fd2 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,7 @@ yarn-error.log .env* env* !.env.example +!.env.recoverable-preview # testing modules/ @@ -78,4 +79,4 @@ modules/ !.yarn/plugins !.yarn/releases !.yarn/sdks -!.yarn/versions \ No newline at end of file +!.yarn/versions diff --git a/App.tsx b/App.tsx index ccf9d5b84..73bdece34 100644 --- a/App.tsx +++ b/App.tsx @@ -1,71 +1,34 @@ -import { LogBox, Platform } from 'react-native'; -import React, { ReactElement, useEffect } from 'react'; -import { GestureHandlerRootView } from 'react-native-gesture-handler'; -import { StatusBar } from '@gluestack-ui/themed-native-base'; -import { PersistGate } from 'redux-persist/integration/react'; -import { Provider } from 'react-redux'; -import { initConnection, endConnection } from 'react-native-iap'; -import { TorContextProvider } from 'src/context/TorContext'; -import { HCESessionProvider } from 'react-native-hce'; -import { LocalizationProvider } from 'src/context/Localization/LocContext'; -import { AppContextProvider } from 'src/context/AppContext'; -import Navigator from './src/navigation/Navigator'; -import { persistor, store } from './src/store/store'; -import NotificationHandler from 'src/hooks/useNotificationHandler'; -import { SentryWrapper } from 'src/services/sentry'; -import ThemeContextProvider from 'src/context/ThemeContext'; -import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context'; - -LogBox.ignoreLogs([ - "[react-native-gesture-handler] Seems like you're using an old API with gesture components, check out new Gestures system!", - /\b{$Require cycle}\b/gi, - 'Warning: ...', - /.+/s, -]); - -function AndroidProvider({ children }: { children: ReactElement }) { - return Platform.OS === 'android' ? {children} : children; -} +import React from 'react'; +import { Text, View } from 'react-native'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import RecoverableWalletPreviewApp from './src/preview/recoverable-wallet/RecoverableWalletPreviewApp'; +import { getPreviewRuntime } from './src/preview/recoverable-wallet/previewRuntime'; function App() { - useEffect(() => { - initConnection(); - return () => { - endConnection(); - }; - }, []); - - return ( - - - - - - - - - - - - - - - - - + const mode = getPreviewRuntime( + NativeConfig.KEEPER_PREVIEW, + DeviceInfo.getBundleId(), + NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY ); -} -function AppWrapper() { - return ( - - - - - - ); -} + if (mode === 'misconfigured') { + return ( + + + This Keeper Preview build is misconfigured. No wallet features are available. + + + ); + } -const SentryApp = SentryWrapper(AppWrapper); + if (mode === 'preview') { + return ; + } + + // Keep the shipping app's providers and services out of the preview runtime. + const ProductionApp = require('./ProductionApp').default; + return ; +} -export default SentryApp; +export default App; diff --git a/ProductionApp.tsx b/ProductionApp.tsx new file mode 100644 index 000000000..ccf9d5b84 --- /dev/null +++ b/ProductionApp.tsx @@ -0,0 +1,71 @@ +import { LogBox, Platform } from 'react-native'; +import React, { ReactElement, useEffect } from 'react'; +import { GestureHandlerRootView } from 'react-native-gesture-handler'; +import { StatusBar } from '@gluestack-ui/themed-native-base'; +import { PersistGate } from 'redux-persist/integration/react'; +import { Provider } from 'react-redux'; +import { initConnection, endConnection } from 'react-native-iap'; +import { TorContextProvider } from 'src/context/TorContext'; +import { HCESessionProvider } from 'react-native-hce'; +import { LocalizationProvider } from 'src/context/Localization/LocContext'; +import { AppContextProvider } from 'src/context/AppContext'; +import Navigator from './src/navigation/Navigator'; +import { persistor, store } from './src/store/store'; +import NotificationHandler from 'src/hooks/useNotificationHandler'; +import { SentryWrapper } from 'src/services/sentry'; +import ThemeContextProvider from 'src/context/ThemeContext'; +import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context'; + +LogBox.ignoreLogs([ + "[react-native-gesture-handler] Seems like you're using an old API with gesture components, check out new Gestures system!", + /\b{$Require cycle}\b/gi, + 'Warning: ...', + /.+/s, +]); + +function AndroidProvider({ children }: { children: ReactElement }) { + return Platform.OS === 'android' ? {children} : children; +} + +function App() { + useEffect(() => { + initConnection(); + return () => { + endConnection(); + }; + }, []); + + return ( + + + + + + + + + + + + + + + + + + ); +} + +function AppWrapper() { + return ( + + + + + + ); +} + +const SentryApp = SentryWrapper(AppWrapper); + +export default SentryApp; diff --git a/android/app/build.gradle b/android/app/build.gradle index e8ead00b0..660937035 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,9 +1,20 @@ apply plugin: "com.android.application" apply plugin: "com.facebook.react" apply plugin: 'com.google.gms.google-services' +// Keep the recoverable-wallet preview on its checked-in, non-production settings. +project.ext.envConfigFiles = [ + recoverablepreviewdebug: ".env.recoverable-preview", + recoverablepreviewrelease: ".env.recoverable-preview", +] apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" apply plugin: 'kotlin-android' +def previewAbiOverride = project.hasProperty('keeperPreviewAbis') && + gradle.startParameter.taskNames.any { it.toLowerCase().contains('recoverablepreview') } +def nativeAbis = previewAbiOverride + ? project.property('keeperPreviewAbis').split(',').toList() + : ['arm64-v8a', 'x86_64', 'x86', 'armeabi-v7a'] + /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. @@ -96,6 +107,7 @@ android { namespace "io.hexawallet.keeper" defaultConfig { applicationId "io.hexawallet.keeper" + buildConfigField "boolean", "IS_RECOVERABLE_PREVIEW", "false" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 621 @@ -104,7 +116,7 @@ android { missingDimensionStrategy 'store', 'play' multiDexEnabled true ndk { - abiFilters 'arm64-v8a', 'x86_64', 'x86', 'armeabi-v7a' + abiFilters(*nativeAbis) } } lintOptions { @@ -152,9 +164,39 @@ android { targetSdkVersion rootProject.ext.targetSdkVersion resValue "string", "build_config_package", "io.hexawallet.keeper" } + recoverablePreview { + minSdkVersion rootProject.ext.minSdkVersion + applicationId "io.hexawallet.keeper.recoverablepreview" + targetSdkVersion rootProject.ext.targetSdkVersion + buildConfigField "boolean", "IS_RECOVERABLE_PREVIEW", "true" + resValue "string", "build_config_package", "io.hexawallet.keeper" + } } } +// A preview APK must never be built with a production or developer .env override. +afterEvaluate { + tasks.matching { it.name in ['preRecoverablePreviewDebugBuild', 'preRecoverablePreviewReleaseBuild'] } + .configureEach { + doFirst { + def expected = [ + KEEPER_PREVIEW: 'true', + KEEPER_PREVIEW_TESTNET_ONLY: 'true', + ENVIRONMENT: 'DEVELOPMENT', + RELAY: 'http://127.0.0.1:1/', + SIGNING_SERVER_TESTNET: 'http://127.0.0.1:1/', + SIGNING_SERVER_MAINNET: 'http://127.0.0.1:1/', + CHANNEL_URL: 'http://127.0.0.1:1/', + ] + expected.each { key, value -> + if (project.env.get(key) != value) { + throw new GradleException("Recoverable preview requires .env.recoverable-preview (${key})") + } + } + } + } +} + repositories{ mavenLocal() diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml index 594604506..fdb0c092e 100644 --- a/android/app/src/debug/AndroidManifest.xml +++ b/android/app/src/debug/AndroidManifest.xml @@ -52,15 +52,6 @@ - - - - - - - - - diff --git a/android/app/src/development/AndroidManifest.xml b/android/app/src/development/AndroidManifest.xml new file mode 100644 index 000000000..792d47e89 --- /dev/null +++ b/android/app/src/development/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index de838aa93..97a628e4f 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -48,21 +48,6 @@ android:exported="true" > - - - - - - - - - - - - - - - diff --git a/android/app/src/main/java/com/hexa_keeper/MainApplication.kt b/android/app/src/main/java/com/hexa_keeper/MainApplication.kt index 553fc3dc3..9c0628e36 100644 --- a/android/app/src/main/java/com/hexa_keeper/MainApplication.kt +++ b/android/app/src/main/java/com/hexa_keeper/MainApplication.kt @@ -28,7 +28,8 @@ class MainApplication : Application(), ReactApplication { PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: add(KeepScreenAwakePackage()) - add(CloudBackupPackage()) + // Preview credentials and Drive scope are deliberately not provisioned yet. + if (!BuildConfig.IS_RECOVERABLE_PREVIEW) add(CloudBackupPackage()) } override fun getJSMainModuleName(): String = "index" @@ -60,4 +61,4 @@ class MainApplication : Application(), ReactApplication { } } -} \ No newline at end of file +} diff --git a/android/app/src/production/AndroidManifest.xml b/android/app/src/production/AndroidManifest.xml new file mode 100644 index 000000000..792d47e89 --- /dev/null +++ b/android/app/src/production/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/recoverablePreview/AndroidManifest.xml b/android/app/src/recoverablePreview/AndroidManifest.xml new file mode 100644 index 000000000..230c36e11 --- /dev/null +++ b/android/app/src/recoverablePreview/AndroidManifest.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + diff --git a/android/app/src/recoverablePreview/google-services.json b/android/app/src/recoverablePreview/google-services.json new file mode 100644 index 000000000..709a54110 --- /dev/null +++ b/android/app/src/recoverablePreview/google-services.json @@ -0,0 +1,22 @@ +{ + "project_info": { + "project_number": "000000000000", + "project_id": "keeper-recoverable-preview-local" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:000000000000:android:0000000000000000", + "android_client_info": { + "package_name": "io.hexawallet.keeper.recoverablepreview" + } + }, + "api_key": [ + { + "current_key": "LOCAL_PREVIEW_NO_REMOTE_SERVICE" + } + ] + } + ], + "configuration_version": "1" +} diff --git a/android/app/src/recoverablePreview/res/values/strings.xml b/android/app/src/recoverablePreview/res/values/strings.xml new file mode 100644 index 000000000..b2071c907 --- /dev/null +++ b/android/app/src/recoverablePreview/res/values/strings.xml @@ -0,0 +1,5 @@ + + Keeper Preview + keeperrecoverablepreview + /app/recoverable-preview + diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index facecff72..b356d171c 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -1,6 +1,24 @@ # Recoverable Wallet — parallel Keeper preview -Status: **parallel development stream, planning and isolated preview setup**. Not a released feature, not a security-reviewed wallet, and not an OpenSpec implementation package. Public name is undecided ("Recoverable Wallet" is a working term). +Status (8 October 2026): **first client preview implemented; Android package built; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. Public name is undecided ("Recoverable Wallet" is a working term). + +## First client checkpoint + +- The separate preview app starts at **Add Wallet** and walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. +- TAPSIGNER, Satochip, Jade, and Coldcard appear with their existing Keeper transport choices. The UI says policy verification and full Recoverable Wallet compatibility remain unproven. Every simulated status, error, and completion is labeled. +- The app entry requires the exact preview package ID and testnet-only preview flags. Normal Keeper continues through its original app component. The preview loads no wallet store, cloud backup, signing, or server client. The native preview identifiers are distinct, the Android CloudBackup module is disabled, and the iOS preview has no iCloud entitlement. See [native-preview.md](native-preview.md). +- An arm64 Android debug APK with an embedded JavaScript bundle was built and its package identity, signature, and merged manifest were checked. It installed and ran beside an existing Keeper development app on an Android emulator. Side-by-side installation with production Keeper on a physical device remains unverified. The iOS preview scheme, identifier, plist, and entitlements are configured, but an iOS build has not been run: this checkout lacks matching Pods and has insufficient free disk space for a safe fresh install/build. + +| Evidence | Current result | +| --- | --- | +| Simulated client flow | Automated walkthrough covers four hardware choices, cancel/resume, connection error, inheritance choice, and final review. | +| Startup boundary and related regressions | 27 focused Jest tests pass across the preview, testnet header, and Recovery Key migration suites. | +| Native build | Android arm64 debug APK built with embedded JS, installed and launched on an arm64 emulator; iOS scheme configuration inspected, build pending. | +| Small-screen rendering | Android emulator walkthrough passed at 320dp width and 1.6× system font: statuses, four hardware choices, simulated error, inheritance, review, and completion remained scrollable and actionable. The Jest content check alone does not establish rendered layout. | +| Physical devices and production side-by-side installation | Pending. The emulator had Keeper development installed, not production Keeper. | +| Cryptography, cloud read-back, physical hardware, security review | Pending; no such functions are represented as complete in this preview. | + +The next owner test is to install the Android APK beside normal Keeper, walk through both inheritance choices and a simulated error, verify text and controls at a small screen width with larger system font, then uninstall Preview and confirm the normal app and backups remain intact. Equivalent iOS testing follows a fresh matching Pods install, simulator/device build, and preview App ID/provisioning setup. Do not use real wallet funds or production recovery material in either preview. ## Owner decision (8 October 2026) @@ -52,4 +70,4 @@ Each checkpoint may be smaller than the grouping above to keep visible feedback ## Immediate next action -Build the separate app-flavor / package identity and local navigable testnet preview **without touching any server repository or production recovery service**. Validate installs alongside production Keeper and separate cloud storage before testing on a real device. Do not represent this README or branch alone as an installable or functional preview. +Run the native device checks in [native-preview.md](native-preview.md), especially side-by-side installation and small-screen accessibility. Finish the iOS build with matching dependencies and separate provisioning. Keep real signing, cloud recovery, and server protocol work gated by their own tests and review; do not change SigningServer or Relay while awaiting Adam's contribution and an owner decision. diff --git a/docs/preview/recoverable-wallet/native-preview.md b/docs/preview/recoverable-wallet/native-preview.md new file mode 100644 index 000000000..777aecb75 --- /dev/null +++ b/docs/preview/recoverable-wallet/native-preview.md @@ -0,0 +1,44 @@ +# Native preview packaging (milestone 1) + +The preview runs the simulated Recoverable Wallet flow only. It creates no wallet, has no signing or recovery protocol, and cannot reach Keeper's production server endpoints from its checked-in configuration. + +| Platform | Preview identity | Build entry | Storage/cloud boundary | +| --- | --- | --- | --- | +| Android | `io.hexawallet.keeper.recoverablepreview` | `yarn androidRecoverablePreview` / `:app:assembleRecoverablePreviewDebug` | Separate Android app sandbox and Keystore namespace. The native `CloudBackup` module is not registered, Google Drive sign-in is unavailable, and the flavor has a local-only placeholder Firebase configuration. No production backup or app links are registered. | +| iOS | `io.hexawallet.hexakeeper.recoverablepreview` | `yarn iosRecoverablePreview` / `hexa_keeper_recoverable_preview` scheme | Separate app sandbox and default Keychain access group. Preview entitlements contain no iCloud, associated domains or push capability. Preview build settings skip Firebase configuration and include a build phase to remove the development `GoogleService-Info.plist`. The simulator build is still unverified. | + +Both builds use the checked-in `.env.recoverable-preview` file. It sets `KEEPER_PREVIEW=true`, `KEEPER_PREVIEW_TESTNET_ONLY=true` and local unreachable service URLs. The preview entry also checks the exact native bundle/application ID before showing the flow; mismatches show a locked error screen. The preview runtime does not initialize the normal Keeper app or its wallet store. + +## Build and install + +From the repository root after installing JS dependencies: + +```sh +yarn androidRecoverablePreview +yarn iosRecoverablePreview +``` + +For an Android APK without launching an emulator: + +```sh +cd android +ENVFILE=.env.recoverable-preview ./gradlew :app:assembleRecoverablePreviewDebug +``` + +For a smaller Android device APK, use `-PkeeperPreviewAbis=arm64-v8a -PreactNativeArchitectures=arm64-v8a` with that Gradle command. The default flavor retains all four configured ABIs. + +The local verification worktree shared `node_modules` through a symlink. Metro required a temporary symlink watch-folder setting for that build; it was removed afterward. A normal dependency installation in this checkout avoids that local workaround. + +The Android package must be installed alongside production Keeper and verified on a device before calling the milestone device-tested. The iOS scheme is configured for the simulator, but a simulator build has not yet completed. A signed physical-device build requires an Apple App ID and provisioning profile for `io.hexawallet.hexakeeper.recoverablepreview`; distribution access must be checked with the Keeper team. Neither cloud backup nor a physical hardware connection is claimed by this milestone. + +Local Android emulator verification on 8 October 2026: the arm64 APK installed, launched from its embedded JavaScript bundle, and completed the simulated walkthrough at 320dp width with 1.6× system text. The emulator already had `io.hexawallet.keeper.development` installed; both package IDs remained distinct. The error, inheritance, review, and completion controls were reachable by scrolling. Physical-device installation, production Keeper co-installation, and real storage/keychain separation still require device checks. + +Before future cloud backup work, register a dedicated iCloud container for the preview App ID and dedicated Google OAuth/Drive credentials. Keep access disabled until read-back and cross-app isolation are verified on real devices. Do not reuse Keeper's production or development cloud identities. + +## Native checks + +1. Confirm production Keeper and Keeper Preview install simultaneously without replacing each other. +2. Confirm the preview icon/name is `Keeper Preview`, has no production deep link/backup intent, and starts directly in the simulated flow. +3. Check iOS Keychain and Android app data remain inaccessible to the other app. On iOS, inspect the signed preview entitlements; they must contain no production iCloud or Keychain group. +4. Confirm both preview backends use only local unreachable URLs and the UI has no mainnet control, wallet creation, signing, or cloud-backup action. +5. Uninstall Preview and confirm production Keeper and its wallet/backups remain intact. diff --git a/index.js b/index.js index e352be378..b7d8025f2 100644 --- a/index.js +++ b/index.js @@ -14,9 +14,17 @@ import { Svg } from 'react-native-svg'; import App from './App'; import { name as appName } from './app.json'; import { enableAndroidFontFix } from './AndroidFontFix'; -import { initSentrySDK } from 'src/services/sentry'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; -initSentrySDK(); +// No production telemetry is initialized for the isolated preview package. +const isRecoverablePreview = + NativeConfig.KEEPER_PREVIEW === 'true' || + NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY === 'true' || + DeviceInfo.getBundleId().endsWith('.recoverablepreview'); +if (!isRecoverablePreview) { + require('src/services/sentry').initSentrySDK(); +} enableAndroidFontFix(); Input.defaultProps = Input.defaultProps || {}; diff --git a/ios/Podfile b/ios/Podfile index b0e96375f..db11d274a 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -9,6 +9,11 @@ require Pod::Executable.execute_command('node', ['-p', )', __dir__]).strip platform :ios, 15.1 +project 'hexa_keeper.xcodeproj', + 'Debug' => :debug, + 'Release' => :release, + 'RecoverablePreviewDebug' => :debug, + 'RecoverablePreviewRelease' => :release prepare_react_native_project! # Required by RNFirebase when static frameworks are enabled via USE_FRAMEWORKS. diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj index 7f0b8da75..e5b76d957 100644 --- a/ios/hexa_keeper.xcodeproj/project.pbxproj +++ b/ios/hexa_keeper.xcodeproj/project.pbxproj @@ -350,6 +350,7 @@ 8EBB6A86DEA895EEFA0939C0 /* [CP] Embed Pods Frameworks */, 5ABA2DEEAC8D206BDE9D1A6B /* [CP] Copy Pods Resources */, 917FB4A01F8341AE0ADBBA05 /* [CP-User] [RNFB] Core Configuration */, + 34C436D21ADC9404B983EA40 /* Remove cloud credentials from recoverable preview */, ); buildRules = ( ); @@ -466,6 +467,24 @@ shellPath = /bin/zsh; shellScript = "set -e\n# Make sure system tools like awk, grep, cut are available\nexport PATH=\"/usr/bin:/bin:/usr/sbin:/sbin:$PATH\"\nexport NODE_BINARY=/opt/homebrew/bin/node\n../node_modules/react-native/scripts/react-native-xcode.sh\n"; }; + 34C436D21ADC9404B983EA40 /* Remove cloud credentials from recoverable preview */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = "Remove cloud credentials from recoverable preview"; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "case \"${CONFIGURATION}\" in\n RecoverablePreview*)\n rm -f \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/GoogleService-Info.plist\"\n rm -f \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/hexa_keeper_dev-Info.plist\"\n ;;\nesac\n"; + }; 3B72837E09FDCE8AE9B64260 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -994,6 +1013,424 @@ }; name = Release; }; + 568042B9DFD49689BEBBFD5A /* RecoverablePreviewDebug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CC = ""; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_CXX_LANGUAGE_STANDARD = "c++20"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CXX = ""; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = i386; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.4; + LD = ""; + LDPLUSPLUS = ""; + LD_RUNPATH_SEARCH_PATHS = ( + /usr/lib/swift, + "$(inherited)", + ); + LIBRARY_SEARCH_PATHS = ( + "\"$(SDKROOT)/usr/lib/swift\"", + "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", + "\"$(inherited)\"", + ); + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_CFLAGS = "$(inherited)"; + OTHER_CPLUSPLUSFLAGS = "$(inherited)"; + OTHER_LDFLAGS = "$(inherited)"; + REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native"; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG"; + USE_HERMES = true; + }; + name = RecoverablePreviewDebug; + }; + 64DC3D260A07EFC1B05F5853 /* RecoverablePreviewRelease */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CC = ""; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_CXX_LANGUAGE_STANDARD = "c++20"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = YES; + CXX = ""; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = i386; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.4; + LD = ""; + LDPLUSPLUS = ""; + LD_RUNPATH_SEARCH_PATHS = ( + /usr/lib/swift, + "$(inherited)", + ); + LIBRARY_SEARCH_PATHS = ( + "\"$(SDKROOT)/usr/lib/swift\"", + "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", + "\"$(inherited)\"", + ); + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_CFLAGS = "$(inherited)"; + OTHER_CPLUSPLUSFLAGS = "$(inherited)"; + OTHER_LDFLAGS = "$(inherited)"; + REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native"; + SDKROOT = iphoneos; + USE_HERMES = true; + VALIDATE_PRODUCT = YES; + }; + name = RecoverablePreviewRelease; + }; + 70C1313EE36557C9AD31140A /* RecoverablePreviewRelease */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DA190250F1EBDD229E110BFA /* Pods-hexa_keeper_dev.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = "dev-AppIcon"; + ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = hexa_keeper_recoverable_preview.entitlements; + CODE_SIGN_IDENTITY = "Apple Distribution"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Distribution"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 614; + DEVELOPMENT_TEAM = Y5TCB759QL; + "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; + ENVFILE = "$(SRCROOT)/../.env.recoverable-preview"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + "KEEPER_RECOVERABLE_PREVIEW=1", + ); + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"${PODS_ROOT}/Headers/Public\"", + "\"${PODS_ROOT}/Headers/Public/BVLinearGradient\"", + "\"${PODS_ROOT}/Headers/Public/CocoaAsyncSocket\"", + "\"${PODS_ROOT}/Headers/Public/DoubleConversion\"", + "\"${PODS_ROOT}/Headers/Public/FBLazyVector\"", + "\"${PODS_ROOT}/Headers/Public/Firebase\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseCore\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseCoreDiagnostics\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseInstallations\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseMessaging\"", + "\"${PODS_ROOT}/Headers/Public/GoogleDataTransport\"", + "\"${PODS_ROOT}/Headers/Public/GoogleUtilities\"", + "\"${PODS_ROOT}/Headers/Public/MMKV\"", + "\"${PODS_ROOT}/Headers/Public/MMKVCore\"", + "\"${PODS_ROOT}/Headers/Public/MultiplatformBleAdapter\"", + "\"${PODS_ROOT}/Headers/Public/PromisesObjC\"", + "\"${PODS_ROOT}/Headers/Public/QrCode\"", + "\"${PODS_ROOT}/Headers/Public/RCT-Folly\"", + "\"${PODS_ROOT}/Headers/Public/RCTRequired\"", + "\"${PODS_ROOT}/Headers/Public/RCTTypeSafety\"", + "\"${PODS_ROOT}/Headers/Public/RNCClipboard\"", + "\"${PODS_ROOT}/Headers/Public/RNDeviceInfo\"", + "\"${PODS_ROOT}/Headers/Public/RNFBApp\"", + "\"${PODS_ROOT}/Headers/Public/RNFBMessaging\"", + "\"${PODS_ROOT}/Headers/Public/RNFS\"", + "\"${PODS_ROOT}/Headers/Public/RNGestureHandler\"", + "\"${PODS_ROOT}/Headers/Public/RNIap\"", + "\"${PODS_ROOT}/Headers/Public/RNKeychain\"", + "\"${PODS_ROOT}/Headers/Public/RNLocalize\"", + "\"${PODS_ROOT}/Headers/Public/RNPermissions\"", + "\"${PODS_ROOT}/Headers/Public/RNReanimated\"", + "\"${PODS_ROOT}/Headers/Public/RNSVG\"", + "\"${PODS_ROOT}/Headers/Public/RNScreens\"", + "\"${PODS_ROOT}/Headers/Public/RNSentry\"", + "\"${PODS_ROOT}/Headers/Public/React-Codegen\"", + "\"${PODS_ROOT}/Headers/Public/React-Core\"", + "\"${PODS_ROOT}/Headers/Public/React-RCTBlob\"", + "\"${PODS_ROOT}/Headers/Public/React-RCTText\"", + "\"${PODS_ROOT}/Headers/Public/React-callinvoker\"", + "\"${PODS_ROOT}/Headers/Public/React-cxxreact\"", + "\"${PODS_ROOT}/Headers/Public/React-jsi\"", + "\"${PODS_ROOT}/Headers/Public/React-jsiexecutor\"", + "\"${PODS_ROOT}/Headers/Public/React-jsinspector\"", + "\"${PODS_ROOT}/Headers/Public/React-logger\"", + "\"${PODS_ROOT}/Headers/Public/React-perflogger\"", + "\"${PODS_ROOT}/Headers/Public/React-runtimeexecutor\"", + "\"${PODS_ROOT}/Headers/Public/ReactCommon\"", + "\"${PODS_ROOT}/Headers/Public/RealmJS\"", + "\"${PODS_ROOT}/Headers/Public/Sentry\"", + "\"${PODS_ROOT}/Headers/Public/SocketRocket\"", + "\"${PODS_ROOT}/Headers/Public/Yoga\"", + "\"${PODS_ROOT}/Headers/Public/YogaKit\"", + "\"${PODS_ROOT}/Headers/Public/fmt\"", + "\"${PODS_ROOT}/Headers/Public/glog\"", + "\"${PODS_ROOT}/Headers/Public/libevent\"", + "\"${PODS_ROOT}/Headers/Public/nanopb\"", + "\"${PODS_ROOT}/Headers/Public/react-native-biometrics\"", + "\"${PODS_ROOT}/Headers/Public/react-native-ble-plx\"", + "\"${PODS_ROOT}/Headers/Public/react-native-camera\"", + "\"${PODS_ROOT}/Headers/Public/react-native-config\"", + "\"${PODS_ROOT}/Headers/Public/react-native-document-picker\"", + "\"${PODS_ROOT}/Headers/Public/react-native-get-random-values\"", + "\"${PODS_ROOT}/Headers/Public/react-native-image-picker\"", + "\"${PODS_ROOT}/Headers/Public/react-native-mmkv\"", + "\"${PODS_ROOT}/Headers/Public/react-native-nfc-manager\"", + "\"${PODS_ROOT}/Headers/Public/react-native-randombytes\"", + "\"${PODS_ROOT}/Headers/Public/react-native-safe-area-context\"", + "\"${PODS_ROOT}/Headers/Public/react-native-tcp-socket\"", + "\"${PODS_ROOT}/Headers/Public/react-native-video\"", + "\"${PODS_XCFRAMEWORKS_BUILD_DIR}/RealmJS/Headers\"", + "\"$(PODS_TARGET_SRCROOT)/include/\"", + "\"$(PODS_ROOT)/DoubleConversion\"", + "$(inherited)", + "${PODS_ROOT}/Firebase/CoreOnly/Sources", + "\"$(PODS_ROOT)/boost\"", + "\"$(PODS_ROOT)/boost\"", + "\"$(PODS_ROOT)/boost-for-react-native\"", + "\"$(PODS_ROOT)/glog\"", + "\"$(PODS_ROOT)/RCT-Folly\"", + "\"${PODS_ROOT}/Headers/Public/React-hermes\"", + "\"${PODS_ROOT}/Headers/Public/hermes-engine\"", + "\"$(PODS_ROOT)/Headers/Private/React-Core\"", + "\"$(SRCROOT)\"", + ); + INFOPLIST_FILE = "hexa_keeper_recoverable_preview-Info.plist"; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.finance"; + IPHONEOS_DEPLOYMENT_TARGET = 15.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + "$(SDKROOT)/usr/lib/swift", + "$(inherited)", + "$(PROJECT_DIR)", + "\"$(SRCROOT)\"", + ); + MARKETING_VERSION = 2.5.14; + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = io.hexawallet.hexakeeper.recoverablepreview; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; + "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = ""; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) KEEPER_RECOVERABLE_PREVIEW"; + SWIFT_OBJC_BRIDGING_HEADER = "whirlpool/hexa_keeper-Bridging-Header.h"; + SWIFT_OBJC_INTERFACE_HEADER_NAME = "hexa_keeper-Swift.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = RecoverablePreviewRelease; + }; + 82FA56318182CC6412F75F39 /* RecoverablePreviewDebug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FF44D0B6D2E87C0D657DAFA5 /* Pods-hexa_keeper_dev.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = "dev-AppIcon"; + ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = hexa_keeper_recoverable_preview.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 614; + DEVELOPMENT_TEAM = Y5TCB759QL; + "DEVELOPMENT_TEAM[sdk=iphoneos*]" = Y5TCB759QL; + ENABLE_BITCODE = NO; + ENVFILE = "$(SRCROOT)/../.env.recoverable-preview"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + "KEEPER_RECOVERABLE_PREVIEW=1", + ); + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "\"${PODS_ROOT}/Headers/Public\"", + "\"${PODS_ROOT}/Headers/Public/BVLinearGradient\"", + "\"${PODS_ROOT}/Headers/Public/CocoaAsyncSocket\"", + "\"${PODS_ROOT}/Headers/Public/DoubleConversion\"", + "\"${PODS_ROOT}/Headers/Public/FBLazyVector\"", + "\"${PODS_ROOT}/Headers/Public/Firebase\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseCore\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseCoreDiagnostics\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseInstallations\"", + "\"${PODS_ROOT}/Headers/Public/FirebaseMessaging\"", + "\"${PODS_ROOT}/Headers/Public/GoogleDataTransport\"", + "\"${PODS_ROOT}/Headers/Public/GoogleUtilities\"", + "\"${PODS_ROOT}/Headers/Public/MMKV\"", + "\"${PODS_ROOT}/Headers/Public/MMKVCore\"", + "\"${PODS_ROOT}/Headers/Public/MultiplatformBleAdapter\"", + "\"${PODS_ROOT}/Headers/Public/PromisesObjC\"", + "\"${PODS_ROOT}/Headers/Public/QrCode\"", + "\"${PODS_ROOT}/Headers/Public/RCT-Folly\"", + "\"${PODS_ROOT}/Headers/Public/RCTRequired\"", + "\"${PODS_ROOT}/Headers/Public/RCTTypeSafety\"", + "\"${PODS_ROOT}/Headers/Public/RNCClipboard\"", + "\"${PODS_ROOT}/Headers/Public/RNDeviceInfo\"", + "\"${PODS_ROOT}/Headers/Public/RNFBApp\"", + "\"${PODS_ROOT}/Headers/Public/RNFBMessaging\"", + "\"${PODS_ROOT}/Headers/Public/RNFS\"", + "\"${PODS_ROOT}/Headers/Public/RNGestureHandler\"", + "\"${PODS_ROOT}/Headers/Public/RNIap\"", + "\"${PODS_ROOT}/Headers/Public/RNKeychain\"", + "\"${PODS_ROOT}/Headers/Public/RNLocalize\"", + "\"${PODS_ROOT}/Headers/Public/RNPermissions\"", + "\"${PODS_ROOT}/Headers/Public/RNReanimated\"", + "\"${PODS_ROOT}/Headers/Public/RNSVG\"", + "\"${PODS_ROOT}/Headers/Public/RNScreens\"", + "\"${PODS_ROOT}/Headers/Public/RNSentry\"", + "\"${PODS_ROOT}/Headers/Public/React-Codegen\"", + "\"${PODS_ROOT}/Headers/Public/React-Core\"", + "\"${PODS_ROOT}/Headers/Public/React-RCTBlob\"", + "\"${PODS_ROOT}/Headers/Public/React-RCTText\"", + "\"${PODS_ROOT}/Headers/Public/React-callinvoker\"", + "\"${PODS_ROOT}/Headers/Public/React-cxxreact\"", + "\"${PODS_ROOT}/Headers/Public/React-jsi\"", + "\"${PODS_ROOT}/Headers/Public/React-jsiexecutor\"", + "\"${PODS_ROOT}/Headers/Public/React-jsinspector\"", + "\"${PODS_ROOT}/Headers/Public/React-logger\"", + "\"${PODS_ROOT}/Headers/Public/React-perflogger\"", + "\"${PODS_ROOT}/Headers/Public/React-runtimeexecutor\"", + "\"${PODS_ROOT}/Headers/Public/ReactCommon\"", + "\"${PODS_ROOT}/Headers/Public/RealmJS\"", + "\"${PODS_ROOT}/Headers/Public/Sentry\"", + "\"${PODS_ROOT}/Headers/Public/SocketRocket\"", + "\"${PODS_ROOT}/Headers/Public/Yoga\"", + "\"${PODS_ROOT}/Headers/Public/YogaKit\"", + "\"${PODS_ROOT}/Headers/Public/fmt\"", + "\"${PODS_ROOT}/Headers/Public/glog\"", + "\"${PODS_ROOT}/Headers/Public/libevent\"", + "\"${PODS_ROOT}/Headers/Public/nanopb\"", + "\"${PODS_ROOT}/Headers/Public/react-native-biometrics\"", + "\"${PODS_ROOT}/Headers/Public/react-native-ble-plx\"", + "\"${PODS_ROOT}/Headers/Public/react-native-camera\"", + "\"${PODS_ROOT}/Headers/Public/react-native-config\"", + "\"${PODS_ROOT}/Headers/Public/react-native-document-picker\"", + "\"${PODS_ROOT}/Headers/Public/react-native-get-random-values\"", + "\"${PODS_ROOT}/Headers/Public/react-native-image-picker\"", + "\"${PODS_ROOT}/Headers/Public/react-native-mmkv\"", + "\"${PODS_ROOT}/Headers/Public/react-native-nfc-manager\"", + "\"${PODS_ROOT}/Headers/Public/react-native-randombytes\"", + "\"${PODS_ROOT}/Headers/Public/react-native-safe-area-context\"", + "\"${PODS_ROOT}/Headers/Public/react-native-tcp-socket\"", + "\"${PODS_ROOT}/Headers/Public/react-native-video\"", + "\"${PODS_XCFRAMEWORKS_BUILD_DIR}/RealmJS/Headers\"", + "\"$(PODS_TARGET_SRCROOT)/include/\"", + "\"$(PODS_ROOT)/DoubleConversion\"", + "$(inherited)", + "${PODS_ROOT}/Firebase/CoreOnly/Sources", + "\"$(PODS_ROOT)/boost\"", + "\"$(PODS_ROOT)/boost\"", + "\"$(PODS_ROOT)/boost-for-react-native\"", + "\"$(PODS_ROOT)/glog\"", + "\"$(PODS_ROOT)/RCT-Folly\"", + "\"${PODS_ROOT}/Headers/Public/React-hermes\"", + "\"${PODS_ROOT}/Headers/Public/hermes-engine\"", + "\"$(PODS_ROOT)/Headers/Private/React-Core\"", + "\"$(SRCROOT)\"", + ); + INFOPLIST_FILE = "hexa_keeper_recoverable_preview-Info.plist"; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.finance"; + IPHONEOS_DEPLOYMENT_TARGET = 15.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + LIBRARY_SEARCH_PATHS = ( + "$(SDKROOT)/usr/lib/swift", + "$(inherited)", + "$(PROJECT_DIR)", + "\"$(SRCROOT)\"", + ); + MARKETING_VERSION = 2.5.14; + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = io.hexawallet.hexakeeper.recoverablepreview; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; + "PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = ""; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) KEEPER_RECOVERABLE_PREVIEW"; + SWIFT_OBJC_BRIDGING_HEADER = "whirlpool/hexa_keeper-Bridging-Header.h"; + SWIFT_OBJC_INTERFACE_HEADER_NAME = "hexa_keeper-Swift.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = RecoverablePreviewDebug; + }; 83CBBA201A601CBA00E9B192 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -1424,6 +1861,8 @@ buildConfigurations = ( 83CBBA201A601CBA00E9B192 /* Debug */, 83CBBA211A601CBA00E9B192 /* Release */, + 568042B9DFD49689BEBBFD5A /* RecoverablePreviewDebug */, + 64DC3D260A07EFC1B05F5853 /* RecoverablePreviewRelease */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1433,6 +1872,8 @@ buildConfigurations = ( F49B77F82848DF5200F9AFBD /* Debug */, F49B77F92848DF5200F9AFBD /* Release */, + 82FA56318182CC6412F75F39 /* RecoverablePreviewDebug */, + 70C1313EE36557C9AD31140A /* RecoverablePreviewRelease */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/ios/hexa_keeper.xcodeproj/xcshareddata/xcschemes/hexa_keeper_recoverable_preview.xcscheme b/ios/hexa_keeper.xcodeproj/xcshareddata/xcschemes/hexa_keeper_recoverable_preview.xcscheme new file mode 100644 index 000000000..5f93a9f78 --- /dev/null +++ b/ios/hexa_keeper.xcodeproj/xcshareddata/xcschemes/hexa_keeper_recoverable_preview.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/hexa_keeper/AppDelegate.mm b/ios/hexa_keeper/AppDelegate.mm index 2e26ca1a9..224086a40 100644 --- a/ios/hexa_keeper/AppDelegate.mm +++ b/ios/hexa_keeper/AppDelegate.mm @@ -27,7 +27,9 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( [[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"]; [[NSUserDefaults standardUserDefaults] synchronize]; } +#if !KEEPER_RECOVERABLE_PREVIEW [FIRApp configure]; +#endif return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @@ -62,4 +64,4 @@ - (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull N restorationHandler:restorationHandler]; } -@end \ No newline at end of file +@end diff --git a/ios/hexa_keeper_recoverable_preview-Info.plist b/ios/hexa_keeper_recoverable_preview-Info.plist new file mode 100644 index 000000000..85d0a4dfe --- /dev/null +++ b/ios/hexa_keeper_recoverable_preview-Info.plist @@ -0,0 +1,109 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + Keeper Preview + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconName + AppIcons + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleSignature + ???? + CFBundleURLTypes + + + CFBundleTypeRole + Editor + CFBundleURLName + keeperrecoverablepreview + CFBundleURLSchemes + + keeperrecoverablepreview + + + + CFBundleVersion + 614 + ITSAppUsesNonExemptEncryption + + LSApplicationQueriesSchemes + + itms-apps + orbot + + LSRequiresIPhoneOS + + NFCReaderUsageDescription + Allow $(PRODUCT_NAME) to interact with nearby NFC devices + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + NSAllowsLocalNetworking + + + NSCameraUsageDescription + Please allow camera access for QR scanner + NSContactsUsageDescription + ContactsList needs your permission to access your contacts + NSFaceIDUsageDescription + Allow $(PRODUCT_NAME) requires FaceID access to allows you quick and secure access. + NSPhotoLibraryUsageDescription + Please allow photo library access to campture screenshots and send app feedback + RCTNewArchEnabled + + UIAppFonts + + Lora-Medium.ttf + Inter-Bold.ttf + Inter-BoldItalic.ttf + Inter-Italic.ttf + Inter-Light.ttf + Inter-LightItalic.ttf + Lora-MediumItalic.ttf + Inter-Regular.ttf + Lora-SemiBold.ttf + Lora-SemiBoldItalic.ttf + + UILaunchStoryboardName + LaunchScreen + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + UIViewControllerBasedStatusBarAppearance + + com.apple.developer.nfc.readersession.iso7816.select-identifiers + + D2760000850100 + D2760000850101 + f0436f696e6b697465434152447631 + 5361746f43686970 + + FirebaseAppDelegateProxyEnabled + + FirebaseMessagingAutoInitEnabled + + FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED + + KeeperRecoverablePreview + + + diff --git a/ios/hexa_keeper_recoverable_preview.entitlements b/ios/hexa_keeper_recoverable_preview.entitlements new file mode 100644 index 000000000..0c67376eb --- /dev/null +++ b/ios/hexa_keeper_recoverable_preview.entitlements @@ -0,0 +1,5 @@ + + + + + diff --git a/package.json b/package.json index d192ee46f..62dff2f1b 100644 --- a/package.json +++ b/package.json @@ -15,10 +15,14 @@ "androidDevelopmentRelease": "ENVFILE=.env react-native run-android --mode=developmentRelease --appIdSuffix=development", "androidProductionDebug": "ENVFILE=.env react-native run-android --mode=productionDebug", "androidProductionRelease": "ENVFILE=.env react-native run-android --mode=productionRelease", + "androidRecoverablePreview": "ENVFILE=.env.recoverable-preview react-native run-android --mode=recoverablePreviewDebug --appId=io.hexawallet.keeper.recoverablepreview", + "iosRecoverablePreview": "ENVFILE=.env.recoverable-preview react-native run-ios --scheme=hexa_keeper_recoverable_preview --mode=RecoverablePreviewDebug --simulator 'iPhone 16'", "uninstall ios": "xcrun simctl uninstall booted io.hexawallet.keeper", "uninstall ios:dev": "xcrun simctl uninstall booted io.hexawallet.hexakeeper.dev", "uninstall android": "adb uninstall io.hexawallet.bitcoinkeeper", "uninstall android:dev": "adb uninstall io.hexawallet.keeper.development", + "uninstall android:recoverable-preview": "adb uninstall io.hexawallet.keeper.recoverablepreview", + "uninstall ios:recoverable-preview": "xcrun simctl uninstall booted io.hexawallet.hexakeeper.recoverablepreview", "release android dev": "cd android && ENVFILE=.env bundle exec fastlane dev --env dev", "release android prod": "cd android && ENVFILE=.env.production bundle exec fastlane live --env production", "release ios dev": "cd ios && ENVFILE=.env bundle exec fastlane dev --env dev", diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx new file mode 100644 index 000000000..551a4ad86 --- /dev/null +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -0,0 +1,547 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { BackHandler, PixelRatio, Pressable, ScrollView, StyleSheet, View } from 'react-native'; +import { NativeBaseProvider, useColorMode } from '@gluestack-ui/themed-native-base'; +import { GestureHandlerRootView } from 'react-native-gesture-handler'; +import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context'; +import Text from 'src/components/KeeperText'; +import ScreenWrapper from 'src/components/ScreenWrapper'; +import { customTheme } from 'src/navigation/themes'; +import Colors from 'src/theme/Colors'; +import { + HARDWARE_CHOICES, + initialPreviewDraft, + PreviewAction, + PreviewDraft, + reducePreviewDraft, +} from './previewFlow'; + +type Palette = { + background: string; + card: string; + text: string; + muted: string; + border: string; + accent: string; + warning: string; +}; + +function PreviewText({ children, style, color, ...props }: any) { + const fontScale = Math.min(PixelRatio.getFontScale(), 2); + const textStyle = StyleSheet.flatten([styles.bodyText, style]); + return ( + + {children} + + ); +} + +function Panel({ children, palette, selected = false, testID }: any) { + return ( + + {children} + + ); +} + +function ScreenHeading({ + title, + onBack, + palette, +}: { + title: string; + onBack?: () => void; + palette: Palette; +}) { + return ( + + {onBack && ( + + + ‹ + + + )} + + {title} + + + ); +} + +function Banner({ palette, children, testID }: any) { + return ( + + + {children} + + + ); +} + +function LinkAction({ label, onPress, palette, testID }: any) { + return ( + + + {label} + + + ); +} + +function PrimaryAction({ label, onPress, palette, disabled = false }: any) { + return ( + + + {label} + + + ); +} + +function PreviewContent() { + const { colorMode } = useColorMode(); + const dark = colorMode === 'dark'; + const palette: Palette = { + background: dark ? Colors.PrimaryBlack : Colors.primaryCream, + card: dark ? Colors.SecondaryBlack : Colors.brightCream, + text: dark ? Colors.bodyText : Colors.secondaryBlack, + muted: dark ? Colors.darkGrey : Colors.GreenishGrey, + border: dark ? Colors.separator : Colors.greyBorder, + accent: dark ? Colors.mintGreen : Colors.primaryGreen, + warning: dark ? Colors.DeepCharcoalGreen : Colors.dullGreen, + }; + const [inFlow, setInFlow] = useState(false); + const [draft, setDraft] = useState(initialPreviewDraft); + const scrollRef = useRef(null); + const act = (action: PreviewAction) => setDraft((current) => reducePreviewDraft(current, action)); + const exitFlow = () => setInFlow(false); + const back = () => { + if (draft.stage === 'complete') { + act({ type: 'RESET' }); + exitFlow(); + } else if (draft.stage === 'automatic') exitFlow(); + else act({ type: 'BACK' }); + }; + + useEffect(() => { + const subscription = BackHandler.addEventListener('hardwareBackPress', () => { + if (!inFlow) return false; + back(); + return true; + }); + return () => subscription.remove(); + }, [inFlow, draft.stage]); + + useEffect(() => { + scrollRef.current?.scrollTo({ y: 0, animated: false }); + }, [inFlow, draft.stage]); + + const selectedDevice = HARDWARE_CHOICES.find(({ id }) => id === draft.hardware); + const hasDraft = + draft.stage !== 'automatic' || draft.hardware !== null || draft.inheritanceEnabled; + + return ( + + + + + TESTNET PREVIEW · Simulated walkthrough. No wallet, key, address, cloud backup, or server + registration is created. + + + {!inFlow && ( + + + Recoverable Wallet + + + Explore a fixed 2-of-3 wallet with an automatic Mobile Key and Server Key, then choose + your Hardware Key. This preview cannot receive or send bitcoin. + + + + Recoverable Wallet · Preview + + + Choose hardware, consider an optional Inheritance Key, and review the complete + proposed policy. + + + setInFlow(true)} + palette={palette} + /> + {hasDraft && ( + { + act({ type: 'RESET' }); + setInFlow(true); + }} + /> + )} + + Progress can be resumed while this preview stays open. It is cleared when the app + closes. + + + )} + + {inFlow && draft.stage === 'automatic' && ( + + + Automatic Keys + + + The proposed wallet needs 2 of 3 keys to spend. These statuses demonstrate the + intended automatic setup. No key material has been generated. + + + + Mobile Key + + + Ready status · SIMULATED + + + The app would prepare this key automatically. There is no Mobile Key or cloud backup + in this preview. + + + + + Server Key + + + Ready status · SIMULATED + + + No Server Key has been requested or registered. Server Key is one key in your + wallet. Keeper cannot spend your bitcoin with this key alone. + + + act({ type: 'NEXT' })} + palette={palette} + /> + + + )} + + {inFlow && draft.stage === 'hardware' && ( + + + Choose Hardware + + + Choose the last base key. Selecting a device here does not connect it or prove that it + can sign the final policy. + + {HARDWARE_CHOICES.map((choice) => ( + act({ type: 'SELECT_HARDWARE', hardware: choice.id })} + > + + + {choice.id} + + {choice.transport} + {choice.verification} + + + ))} + act({ type: 'NEXT' })} + palette={palette} + /> + + + )} + + {inFlow && draft.stage === 'connect' && ( + + + Connect Hardware + + + + {selectedDevice?.id} + + {selectedDevice?.transport} + + Selected for this walkthrough only. No device has been read, paired, or registered. + + + + Simulate Error shows a sample connection failure. It does not start NFC, camera, file, + or Desktop access. + + {draft.connectionAttempts > 0 && ( + + Simulated error {draft.connectionAttempts}: hardware connection is not implemented. + No hardware was accessed. You can choose another device or continue with the + simulated selection. + + )} + act({ type: 'ATTEMPT_CONNECTION' })} + palette={palette} + /> + act({ type: 'CONTINUE_SIMULATION' })} + palette={palette} + testID="preview-continue-simulation" + /> + act({ type: 'BACK' })} + palette={palette} + testID="preview-choose-another" + /> + + + )} + + {inFlow && draft.stage === 'inheritance' && ( + + + Inheritance Key + + + An Inheritance Key gives your chosen heir or trusted party a delayed access path, + based on the wallet rules you set. + + act({ type: 'SET_INHERITANCE', enabled: !draft.inheritanceEnabled })} + > + + + {draft.inheritanceEnabled ? '✓ Add Inheritance Key' : '○ Add Inheritance Key'} + + + Optional. It does not lower the 2-of-3 spending requirement today. + + + + {draft.inheritanceEnabled && ( + + Selection is simulated. No heir, delay, Inheritance Key, or Miniscript policy is + configured here. + + )} + act({ type: 'NEXT' })} + palette={palette} + /> + + + )} + + {inFlow && draft.stage === 'review' && ( + + + Review Policy + + + Review the complete proposed wallet before any real wallet would be created. This + preview cannot approve or register a policy. + + + + Spending now · 2 of 3 + + Mobile Key · ready status simulated + Server Key · ready status simulated + + {selectedDevice?.id} Hardware Key · selected, not connected + + + Any 2 of these 3 keys would be needed to spend. Keeper cannot spend with Server Key + alone. + + + + + Inheritance · {draft.inheritanceEnabled ? 'selected' : 'not added'} + + + {draft.inheritanceEnabled + ? 'After eligibility, an Inheritance Key and any eligible original signer would form the 2-of-4 spending path. The delay and Miniscript conditions are not configured in this preview.' + : 'The proposed wallet has only the base 2-of-3 spending path.'} + + + + SIMULATED POLICY · No private keys, descriptor, address, backup, transaction, or + server approval exists. Hardware and inheritance compatibility still need physical + testing and security review. + + act({ type: 'NEXT' })} + palette={palette} + /> + + + )} + + {inFlow && draft.stage === 'complete' && ( + + + Walkthrough Complete + + + No wallet was created. No bitcoin can be received or sent from this preview. + + + Your selected hardware and inheritance choice were used only to show the proposed + review. No key, hardware device, cloud service, or Keeper server was accessed. + + act({ type: 'RESET' })} + palette={palette} + /> + + + )} + + + ); +} + +export default function RecoverableWalletPreviewApp() { + return ( + + + + + + + + ); +} + +const styles = StyleSheet.create({ + root: { flex: 1 }, + header: { flexDirection: 'row', alignItems: 'center', minHeight: 46, marginBottom: 8 }, + backButton: { width: 36, minHeight: 44, justifyContent: 'center' }, + backText: { fontSize: 32, lineHeight: 40 }, + headerTitle: { fontSize: 18, fontWeight: '600', flexShrink: 1 }, + scroll: { flex: 1 }, + scrollContent: { paddingBottom: 36 }, + section: { gap: 14, paddingTop: 12 }, + pageTitle: { fontSize: 24, fontWeight: '600' }, + bodyText: { fontSize: 15, lineHeight: 23 }, + cardTitle: { fontSize: 17, fontWeight: '600' }, + panel: { borderRadius: 12, padding: 16, gap: 7 }, + banner: { borderRadius: 10, padding: 14, marginTop: 8 }, + bannerText: { fontSize: 14, lineHeight: 21, fontWeight: '500' }, + status: { fontSize: 13, lineHeight: 19, fontWeight: '600' }, + linkButton: { alignItems: 'center', justifyContent: 'center', minHeight: 44, padding: 8 }, + linkText: { fontSize: 15, fontWeight: '600' }, + primaryButton: { + alignSelf: 'stretch', + alignItems: 'center', + justifyContent: 'center', + minHeight: 52, + paddingVertical: 14, + paddingHorizontal: 16, + borderRadius: 10, + }, + primaryButtonText: { fontSize: 15, fontWeight: '700', textAlign: 'center' }, + note: { fontSize: 13, lineHeight: 20, marginTop: 4 }, +}); diff --git a/src/preview/recoverable-wallet/previewFlow.ts b/src/preview/recoverable-wallet/previewFlow.ts new file mode 100644 index 000000000..da6f84ebd --- /dev/null +++ b/src/preview/recoverable-wallet/previewFlow.ts @@ -0,0 +1,91 @@ +export const HARDWARE_CHOICES = [ + { + id: 'TAPSIGNER', + transport: 'NFC', + verification: 'Signing device; full wallet policy cannot be verified on the card.', + }, + { + id: 'Satochip', + transport: 'NFC', + verification: 'Signing device; full wallet policy cannot be verified on the card.', + }, + { + id: 'Jade', + transport: 'QR or Keeper Desktop USB', + verification: 'Full Recoverable Wallet policy compatibility is not yet verified.', + }, + { + id: 'Coldcard', + transport: 'QR, file, NFC, or Keeper Desktop USB', + verification: 'Full Recoverable Wallet policy compatibility is not yet verified.', + }, +] as const; + +export type PreviewHardware = (typeof HARDWARE_CHOICES)[number]['id']; +export type PreviewStage = + | 'automatic' + | 'hardware' + | 'connect' + | 'inheritance' + | 'review' + | 'complete'; + +export type PreviewDraft = { + stage: PreviewStage; + hardware: PreviewHardware | null; + connectionAttempts: number; + inheritanceEnabled: boolean; +}; + +export const initialPreviewDraft: PreviewDraft = { + stage: 'automatic', + hardware: null, + connectionAttempts: 0, + inheritanceEnabled: false, +}; + +export type PreviewAction = + | { type: 'NEXT' } + | { type: 'BACK' } + | { type: 'SELECT_HARDWARE'; hardware: PreviewHardware } + | { type: 'ATTEMPT_CONNECTION' } + | { type: 'CONTINUE_SIMULATION' } + | { type: 'SET_INHERITANCE'; enabled: boolean } + | { type: 'RESET' }; + +export function reducePreviewDraft(draft: PreviewDraft, action: PreviewAction): PreviewDraft { + switch (action.type) { + case 'RESET': + return initialPreviewDraft; + case 'SELECT_HARDWARE': + return draft.stage === 'hardware' && HARDWARE_CHOICES.some(({ id }) => id === action.hardware) + ? { ...draft, hardware: action.hardware, connectionAttempts: 0 } + : draft; + case 'ATTEMPT_CONNECTION': + return draft.stage === 'connect' + ? { ...draft, connectionAttempts: draft.connectionAttempts + 1 } + : draft; + case 'CONTINUE_SIMULATION': + return draft.stage === 'connect' && draft.hardware + ? { ...draft, stage: 'inheritance' } + : draft; + case 'SET_INHERITANCE': + return draft.stage === 'inheritance' + ? { ...draft, inheritanceEnabled: action.enabled } + : draft; + case 'NEXT': + if (draft.stage === 'automatic') return { ...draft, stage: 'hardware' }; + if (draft.stage === 'hardware' && draft.hardware) return { ...draft, stage: 'connect' }; + if (draft.stage === 'inheritance' && draft.hardware) return { ...draft, stage: 'review' }; + if (draft.stage === 'review' && draft.hardware) return { ...draft, stage: 'complete' }; + return draft; + case 'BACK': + if (draft.stage === 'hardware') return { ...draft, stage: 'automatic' }; + if (draft.stage === 'connect') return { ...draft, stage: 'hardware' }; + if (draft.stage === 'inheritance') return { ...draft, stage: 'connect' }; + if (draft.stage === 'review') return { ...draft, stage: 'inheritance' }; + return draft; + default: + return draft; + } +} diff --git a/src/preview/recoverable-wallet/previewRuntime.ts b/src/preview/recoverable-wallet/previewRuntime.ts new file mode 100644 index 000000000..0573338b2 --- /dev/null +++ b/src/preview/recoverable-wallet/previewRuntime.ts @@ -0,0 +1,21 @@ +export type PreviewRuntime = 'preview' | 'production' | 'misconfigured'; + +export const PREVIEW_BUNDLE_IDS = [ + 'io.hexawallet.keeper.recoverablepreview', + 'io.hexawallet.hexakeeper.recoverablepreview', +]; + +export function getPreviewRuntime( + flag: string | undefined, + bundleId: string, + testnetOnlyFlag: string | undefined +): PreviewRuntime { + const hasPreviewFlag = flag === 'true'; + const hasPreviewIdentity = PREVIEW_BUNDLE_IDS.includes(bundleId); + const hasPreviewSignal = + hasPreviewFlag || testnetOnlyFlag === 'true' || bundleId.endsWith('.recoverablepreview'); + + if (!hasPreviewSignal) return 'production'; + if (!hasPreviewIdentity || !hasPreviewFlag || testnetOnlyFlag !== 'true') return 'misconfigured'; + return 'preview'; +} diff --git a/tests/preview/previewAppBoundary.test.tsx b/tests/preview/previewAppBoundary.test.tsx new file mode 100644 index 000000000..3958cae78 --- /dev/null +++ b/tests/preview/previewAppBoundary.test.tsx @@ -0,0 +1,58 @@ +import React from 'react'; +import { render } from '@testing-library/react-native'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import App from '../../App'; + +jest.mock('react-native-config', () => ({ + KEEPER_PREVIEW: 'true', + KEEPER_PREVIEW_TESTNET_ONLY: 'true', +})); + +jest.mock('react-native-device-info', () => ({ + getBundleId: jest.fn(() => 'io.hexawallet.keeper.recoverablepreview'), +})); + +jest.mock('../../src/preview/recoverable-wallet/RecoverableWalletPreviewApp', () => { + const React = require('react'); + const { Text } = require('react-native'); + return () => Preview only; +}); + +jest.mock('../../ProductionApp', () => { + const React = require('react'); + const { Text } = require('react-native'); + return { __esModule: true, default: () => Regular Keeper }; +}); + +describe('App startup boundary', () => { + afterEach(() => { + (NativeConfig as any).KEEPER_PREVIEW = 'true'; + (NativeConfig as any).KEEPER_PREVIEW_TESTNET_ONLY = 'true'; + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + }); + + test('preview identity starts the isolated client shell', () => { + const screen = render(); + expect(screen.getByTestId('isolated-preview')).toBeTruthy(); + expect(screen.queryByTestId('regular-app')).toBeNull(); + }); + + test('a preview identity without the testnet flag fails closed', () => { + (NativeConfig as any).KEEPER_PREVIEW_TESTNET_ONLY = undefined; + const screen = render(); + expect(screen.getByText(/misconfigured/)).toBeTruthy(); + expect(screen.queryByTestId('regular-app')).toBeNull(); + }); + + test('normal Keeper identity keeps the normal app path', () => { + (NativeConfig as any).KEEPER_PREVIEW = undefined; + (NativeConfig as any).KEEPER_PREVIEW_TESTNET_ONLY = undefined; + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue('io.hexawallet.keeper'); + const screen = render(); + expect(screen.getByTestId('regular-app')).toBeTruthy(); + expect(screen.queryByTestId('isolated-preview')).toBeNull(); + }); +}); diff --git a/tests/preview/recoverableWalletPreview.test.ts b/tests/preview/recoverableWalletPreview.test.ts new file mode 100644 index 000000000..b41198f7d --- /dev/null +++ b/tests/preview/recoverableWalletPreview.test.ts @@ -0,0 +1,85 @@ +import { + getPreviewRuntime, + PREVIEW_BUNDLE_IDS, +} from '../../src/preview/recoverable-wallet/previewRuntime'; +import { + HARDWARE_CHOICES, + initialPreviewDraft, + reducePreviewDraft, +} from '../../src/preview/recoverable-wallet/previewFlow'; + +describe('Recoverable Wallet preview isolation', () => { + test.each(PREVIEW_BUNDLE_IDS)( + 'permits only the matching testnet preview build: %s', + (bundleId) => { + expect(getPreviewRuntime('true', bundleId, 'true')).toBe('preview'); + expect(getPreviewRuntime(undefined, bundleId, 'true')).toBe('misconfigured'); + expect(getPreviewRuntime('true', bundleId, undefined)).toBe('misconfigured'); + } + ); + + test('does not expose preview in the regular app or an accidentally flagged regular build', () => { + expect(getPreviewRuntime(undefined, 'io.hexawallet.keeper', undefined)).toBe('production'); + expect(getPreviewRuntime('true', 'io.hexawallet.keeper', 'true')).toBe('misconfigured'); + expect( + getPreviewRuntime(undefined, 'io.hexawallet.someapp.recoverablepreview', undefined) + ).toBe('misconfigured'); + expect(getPreviewRuntime(undefined, 'io.hexawallet.keeper', 'true')).toBe('misconfigured'); + }); +}); + +describe('Recoverable Wallet walkthrough', () => { + test.each(HARDWARE_CHOICES)('requires a selected $id before final review', ({ id }) => { + const hardwareStage = reducePreviewDraft(initialPreviewDraft, { type: 'NEXT' }); + expect(reducePreviewDraft(hardwareStage, { type: 'NEXT' })).toEqual(hardwareStage); + + const selected = reducePreviewDraft(hardwareStage, { type: 'SELECT_HARDWARE', hardware: id }); + const connectStage = reducePreviewDraft(selected, { type: 'NEXT' }); + expect(connectStage.stage).toBe('connect'); + expect(connectStage.hardware).toBe(id); + expect( + reducePreviewDraft(connectStage, { type: 'ATTEMPT_CONNECTION' }).connectionAttempts + ).toBe(1); + + const inheritanceStage = reducePreviewDraft(connectStage, { type: 'CONTINUE_SIMULATION' }); + const reviewStage = reducePreviewDraft(inheritanceStage, { type: 'NEXT' }); + expect(reviewStage.stage).toBe('review'); + expect(reviewStage.hardware).toBe(id); + expect(reviewStage.inheritanceEnabled).toBe(false); + expect(reducePreviewDraft(reviewStage, { type: 'NEXT' }).stage).toBe('complete'); + }); + + test('inheritance is chosen before one final review and remains editable when going back', () => { + let draft = reducePreviewDraft(initialPreviewDraft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware: 'Satochip' }); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'CONTINUE_SIMULATION' }); + draft = reducePreviewDraft(draft, { type: 'SET_INHERITANCE', enabled: true }); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + expect(draft).toMatchObject({ + stage: 'review', + hardware: 'Satochip', + inheritanceEnabled: true, + }); + + draft = reducePreviewDraft(draft, { type: 'BACK' }); + draft = reducePreviewDraft(draft, { type: 'SET_INHERITANCE', enabled: false }); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + expect(draft).toMatchObject({ stage: 'review', inheritanceEnabled: false }); + }); + + test('a connection attempt never marks hardware connected and a reset discards the draft', () => { + let draft = reducePreviewDraft(initialPreviewDraft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware: 'TAPSIGNER' }); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'ATTEMPT_CONNECTION' }); + draft = reducePreviewDraft(draft, { type: 'ATTEMPT_CONNECTION' }); + expect(draft).toEqual({ + stage: 'connect', + hardware: 'TAPSIGNER', + connectionAttempts: 2, + inheritanceEnabled: false, + }); + expect(reducePreviewDraft(draft, { type: 'RESET' })).toEqual(initialPreviewDraft); + }); +}); diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx new file mode 100644 index 000000000..a9fe41ea6 --- /dev/null +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -0,0 +1,72 @@ +import React from 'react'; +import { Dimensions, PixelRatio, StyleSheet } from 'react-native'; +import { fireEvent, render } from '@testing-library/react-native'; +import RecoverableWalletPreviewApp from '../../src/preview/recoverable-wallet/RecoverableWalletPreviewApp'; + +jest.mock('src/components/ScreenWrapper', () => { + const React = require('react'); + const { View } = require('react-native'); + return ({ children }) => {children}; +}); + +jest.mock('react-native-safe-area-context', () => { + const React = require('react'); + return { + SafeAreaProvider: ({ children }) => <>{children}, + initialWindowMetrics: { insets: { top: 0, right: 0, bottom: 0, left: 0 } }, + }; +}); + +jest.mock('src/components/KeeperText', () => { + const React = require('react'); + const { Text } = require('react-native'); + return ({ children, ...props }) => {children}; +}); + +describe('Recoverable Wallet preview on a small screen', () => { + beforeEach(() => { + jest + .spyOn(Dimensions, 'get') + .mockReturnValue({ width: 320, height: 640, scale: 2, fontScale: 1.6 }); + jest.spyOn(PixelRatio, 'getFontScale').mockReturnValue(1.6); + }); + + test('keeps security copy available, reaches one final review, and resumes after cancel', () => { + const screen = render(); + expect(screen.getByTestId('preview-simulation-banner')).toHaveTextContent( + 'Simulated walkthrough' + ); + fireEvent.press(screen.getByTestId('primary-Start Preview')); + expect(screen.getByTestId('preview-automatic')).toHaveTextContent( + 'No key material has been generated' + ); + const serverWarning = screen.getByText(/Keeper cannot spend your bitcoin with this key alone/); + expect(serverWarning.props.allowFontScaling).toBe(true); + expect(StyleSheet.flatten(serverWarning.props.style).lineHeight).toBeGreaterThan(23); + const primaryLabel = screen.getByText('Continue'); + expect(primaryLabel.props.allowFontScaling).toBe(true); + expect(primaryLabel.props.numberOfLines).toBeUndefined(); + fireEvent.press(screen.getByTestId('primary-Continue')); + expect(screen.getByTestId('primary-Continue').props.accessibilityState.disabled).toBe(true); + fireEvent.press(screen.getByTestId('preview-hardware-Coldcard')); + fireEvent.press(screen.getByTestId('primary-Continue')); + fireEvent.press(screen.getByTestId('primary-Simulate Error')); + expect(screen.getByTestId('preview-connection-error')).toHaveTextContent( + 'No hardware was accessed' + ); + fireEvent.press(screen.getByTestId('primary-Simulate Error')); + expect(screen.getByTestId('preview-connection-error')).toHaveTextContent('Simulated error 2'); + fireEvent.press(screen.getByTestId('preview-cancel')); + fireEvent.press(screen.getByTestId('primary-Resume')); + expect(screen.getByTestId('preview-connect')).toHaveTextContent('Coldcard'); + fireEvent.press(screen.getByTestId('preview-continue-simulation')); + fireEvent.press(screen.getByTestId('preview-inheritance-toggle')); + fireEvent.press(screen.getByTestId('primary-Review Policy')); + expect(screen.getByTestId('preview-review')).toHaveTextContent('Spending now · 2 of 3'); + expect(screen.getByTestId('preview-review')).toHaveTextContent( + 'Inheritance Key and any eligible original signer' + ); + fireEvent.press(screen.getByTestId('primary-Finish Preview')); + expect(screen.getByTestId('preview-complete')).toHaveTextContent('No wallet was created'); + }); +}); From 4da383b59409ccab8fa582710ec6bd669d596d6d Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 22:18:58 +0530 Subject: [PATCH 03/31] Add Seedless wallet chooser and client recovery foundations --- .env.recoverable-preview | 2 + docs/preview/recoverable-wallet/README.md | 15 +- .../recoverable-wallet/policy-draft.md | 11 + .../recoverable-wallet/recovery-contact.md | 33 ++ src/components/WalletCreationChooser.tsx | 246 ++++++++ src/navigation/Navigator.tsx | 2 + src/navigation/types.ts | 1 + .../RecoverableWalletPreviewApp.tsx | 548 ++++++++++++++++-- .../AddWalletScreen/WalletChoiceScreen.tsx | 127 ++++ .../Home/components/Wallet/HomeWallet.tsx | 50 +- .../recoverable/emptyWalletOnboarding.ts | 31 + .../operations/recoverable/mobileKey.ts | 75 +++ .../recoverable/mobileKeyConstants.ts | 10 + .../recoverable/mobileKeyOrdinal.ts | 137 +++++ .../recoverable/contactRecoveryFlow.ts | 444 ++++++++++++++ .../wallets/recoverable/policyDraft.ts | 488 ++++++++++++++++ src/store/sagas/bhr.ts | 15 +- src/store/sagas/settings.ts | 15 +- src/store/sagas/storage.ts | 49 +- .../preview/recoverableWalletScreen.test.tsx | 150 ++++- tests/preview/walletChoiceScreen.test.tsx | 113 ++++ tests/services/emptyWalletNetworkSaga.test.ts | 83 +++ tests/services/emptyWalletOnboarding.test.ts | 63 ++ tests/services/emptyWalletSetupSaga.test.ts | 89 +++ .../recoverable/contactRecoveryFlow.test.ts | 256 ++++++++ .../services/recoverable/policyDraft.test.ts | 221 +++++++ tests/services/recoverableMobileKey.test.ts | 95 +++ .../recoverableMobileKeyOrdinal.test.ts | 85 +++ 28 files changed, 3369 insertions(+), 85 deletions(-) create mode 100644 docs/preview/recoverable-wallet/policy-draft.md create mode 100644 docs/preview/recoverable-wallet/recovery-contact.md create mode 100644 src/components/WalletCreationChooser.tsx create mode 100644 src/screens/AddWalletScreen/WalletChoiceScreen.tsx create mode 100644 src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts create mode 100644 src/services/wallets/operations/recoverable/mobileKey.ts create mode 100644 src/services/wallets/operations/recoverable/mobileKeyConstants.ts create mode 100644 src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts create mode 100644 src/services/wallets/recoverable/contactRecoveryFlow.ts create mode 100644 src/services/wallets/recoverable/policyDraft.ts create mode 100644 tests/preview/walletChoiceScreen.test.tsx create mode 100644 tests/services/emptyWalletNetworkSaga.test.ts create mode 100644 tests/services/emptyWalletOnboarding.test.ts create mode 100644 tests/services/emptyWalletSetupSaga.test.ts create mode 100644 tests/services/recoverable/contactRecoveryFlow.test.ts create mode 100644 tests/services/recoverable/policyDraft.test.ts create mode 100644 tests/services/recoverableMobileKey.test.ts create mode 100644 tests/services/recoverableMobileKeyOrdinal.test.ts diff --git a/.env.recoverable-preview b/.env.recoverable-preview index 5cc8b4fe4..378d6b363 100644 --- a/.env.recoverable-preview +++ b/.env.recoverable-preview @@ -1,6 +1,8 @@ # This file is intentionally public and contains no signing or cloud credentials. KEEPER_PREVIEW=true KEEPER_PREVIEW_TESTNET_ONLY=true +# Reserved for the reviewed, integrated wallet chooser. The current preview shell never runs wallet sagas. +KEEPER_EMPTY_WALLET_ONBOARDING=true ENVIRONMENT=DEVELOPMENT # Fail closed if a regular service client is accidentally reached by the preview shell. RELAY=http://127.0.0.1:1/ diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index b356d171c..4d1fabf78 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -1,10 +1,10 @@ # Recoverable Wallet — parallel Keeper preview -Status (8 October 2026): **first client preview implemented; Android package built; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. Public name is undecided ("Recoverable Wallet" is a working term). +Status (8 October 2026): **isolated client preview and three-choice wallet entry implemented; Android package built for the first checkpoint; iOS package configured but not built**. The latest chooser changes have not yet been packaged in a new APK. This is a simulated walkthrough, not a released or security-reviewed wallet. "Seedless Wallet" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. ## First client checkpoint -- The separate preview app starts at **Add Wallet** and walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. +- The packaged first preview starts at **Add Wallet** and walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. - TAPSIGNER, Satochip, Jade, and Coldcard appear with their existing Keeper transport choices. The UI says policy verification and full Recoverable Wallet compatibility remain unproven. Every simulated status, error, and completion is labeled. - The app entry requires the exact preview package ID and testnet-only preview flags. Normal Keeper continues through its original app component. The preview loads no wallet store, cloud backup, signing, or server client. The native preview identifiers are distinct, the Android CloudBackup module is disabled, and the iOS preview has no iCloud entitlement. See [native-preview.md](native-preview.md). - An arm64 Android debug APK with an embedded JavaScript bundle was built and its package identity, signature, and merged manifest were checked. It installed and ran beside an existing Keeper development app on an Android emulator. Side-by-side installation with production Keeper on a physical device remains unverified. The iOS preview scheme, identifier, plist, and entitlements are configured, but an iOS build has not been run: this checkout lacks matching Pods and has insufficient free disk space for a safe fresh install/build. @@ -20,6 +20,17 @@ Status (8 October 2026): **first client preview implemented; Android package bui The next owner test is to install the Android APK beside normal Keeper, walk through both inheritance choices and a simulated error, verify text and controls at a small screen width with larger system font, then uninstall Preview and confirm the normal app and backups remain intact. Equivalent iOS testing follows a fresh matching Pods install, simulator/device build, and preview App ID/provisioning setup. Do not use real wallet funds or production recovery material in either preview. +## Second client checkpoint in this branch + +- The separate preview app now starts with **no wallet**. Wallets → Add Wallet opens a reusable full-screen choice of **Simple Wallet** (Hot or Cold next), prominent **Seedless Wallet**, and **Advanced Wallet**; Import Wallet remains visible. Simple, Advanced, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. +- The proposed Mobile Key derives deterministically from the existing 12-word Recovery Key through a dedicated, versioned BIP85 child range starting at index 1,000,000. Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Seedless. The helper returns only testnet public signer details and recovery metadata. The pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. +- A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. Its 2-of-3 and delayed 2-of-4 results are explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). +- A client-only Recovery Contact state model covers encrypted-cloud readback receipts, offline retry, invitation/request expiry, approval/decline, and optional recovery-code gating. It stops before cryptographic enrollment or restoration. No contact key, encrypted backup, native cloud container, or independent exchange channel exists yet. See [recovery-contact.md](recovery-contact.md). +- The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. +- Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. + +The latest client code passed **57 focused Jest tests** across chooser/navigation, preview isolation, empty-wallet gates, key derivation, policy review, and contact states, plus **17 existing wallet/Recovery Key regression tests**. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. + ## Owner decision (8 October 2026) Develop a Bitkey-like Recoverable Wallet **in parallel with** the existing R01–R10 work buckets. This stream is **not** a new R11/R12 bucket, and its feature is **not committed to ship in R9/R10**. User-visible progress must be measured by independently installable, manually testable preview builds, not just code review. No existing release is delayed or silently rescoped to fit this feature. diff --git a/docs/preview/recoverable-wallet/policy-draft.md b/docs/preview/recoverable-wallet/policy-draft.md new file mode 100644 index 000000000..8e96eb25e --- /dev/null +++ b/docs/preview/recoverable-wallet/policy-draft.md @@ -0,0 +1,11 @@ +# Public policy draft boundary + +`src/services/wallets/recoverable/policyDraft.ts` validates a proposed testnet 2-of-3 Mobile Key + Hardware Key + Server Key arrangement using public metadata only. Optional Inheritance Key is included **before** the whole-policy review. The module never requests a key, creates a wallet, registers a policy, signs, or funds an address. Every result is `fundable: false`. + +The Mobile Key metadata must match the version 1 BIP85 reservation from Keeper's Recovery Key, outside the existing hot-wallet and USDT ranges. All signers need a testnet BIP48 native-segwit account tpub with serialized depth 4 and final hardened child index `2'`. Duplicate fingerprints or tpubs, private fields, mainnet keys, and unsupported import transports are rejected. A tpub **cannot prove** its claimed earlier derivation ancestors, master fingerprint, device identity, or possession; those need device-specific checks before wallet creation. + +Without Inheritance Key, the review contains Keeper's plain 2-of-3 `VaultScheme`, but no fundable wallet. With Inheritance Key, Keeper's Miniscript policy generator/compiler validates a candidate base 2-of-3 phase and delayed 2-of-4 phase. The review deliberately omits a fundable `MiniscriptScheme` or descriptor. The candidate proves only script compilation and modeled witness paths; it does **not** establish that a particular hardware firmware can display, register, or sign the complete policy. TAPSIGNER, Satochip, and Jade are blocked for this delayed-policy draft because current integrations do not verify the whole policy on-device. Coldcard remains a review candidate, with full hardware-policy compatibility still unproven. The Server Key's genuine public material and registration also remain unavailable until the held server work is reviewed. + +Inheritance activation is an explicit absolute block height or median-time-past value supplied with a chain observation; this module does not choose a default duration or query the chain. The product decision on fixed versus renewed timing is pending. Keeper's existing testnet duration labels are accelerated, so no UI should present a testnet “1 year” setting as a literal year. An absolute delayed path never resets from app activity. Changing that policy later requires migration and an on-chain transfer. + +Focused tests cover testnet-only inputs, public-key origin shape, duplicate rejection, optional delayed script/witness combinations, blocked hardware combinations, future locktime, and the non-fundable result. Actual receive/send, physical signer compatibility, descriptor import into another wallet, chain maturity, and server-independent heir exit still require separate tests and review. diff --git a/docs/preview/recoverable-wallet/recovery-contact.md b/docs/preview/recoverable-wallet/recovery-contact.md new file mode 100644 index 000000000..d7418f84b --- /dev/null +++ b/docs/preview/recoverable-wallet/recovery-contact.md @@ -0,0 +1,33 @@ +# Recovery Contact: client boundary + +Status: **state model only**. `src/services/wallets/recoverable/contactRecoveryFlow.ts` has no key, cloud, contact-transport, or cryptographic implementation. No preview screen may report enrollment or recovery as complete from these states. + +## Proposed independent route + +Recovery Contact is distinct from the Inheritance Key, hardware signer, Server Key, and Keeper Recovery Key. The intended route restores only this wallet's derived Mobile Key, plus the wallet descriptor needed to find its funds. It does not reset Keeper or give the contact a signing role. The user must still pair the recovered Mobile Key with another signer to spend. + +The first security option is access to the user's separate encrypted cloud backup **and** approval from an enrolled contact. A stronger option also requires a user-held recovery code. Both are represented in the state model; neither is selected as a product default yet. The owner must decide whether the extra code is worth its backup burden. With the first option, a malicious contact who also obtains the cloud blob could recover the Mobile Key, though that alone is insufficient for this wallet's 2-of-3 spend. + +An eventual client implementation should generate a fresh random backup encryption key, encrypt the Mobile Key and descriptor with an audited authenticated-encryption implementation, and store only ciphertext in a dedicated preview iCloud/Google Drive location. The contact device keeps a separate recovery credential. Enrollment must cryptographically wrap the backup key to that credential and perform a cloud download plus authenticated decrypt of the stored result. The current reducer checks only that the downloaded ciphertext digest matches the written digest; that is **not** cryptographic readback verification. The existing Keeper CloudBackup module writes configuration PDFs in shared/default storage and cannot be reused for Mobile Key backup. + +On a replacement phone, the client should download the encrypted blob, create an ephemeral replacement-device public key and one-time request, then exchange the request and response directly with the contact by QR or an external share channel. The contact must identify the person asking through a separate, human-verifiable check before approval. A reviewed encryption implementation must bind the contact's response to the wallet, request nonce, expiry, enrolled credential, and replacement-device key. The request and response must work while Keeper SigningServer and Relay are unreachable. A contact approval is not itself a decrypted backup or restored key. + +The request and cloud receipt use a 32-byte public `walletPolicyHash`, not Bitcoin's 4-byte master fingerprint. A future implementation must derive this commitment from the **canonical final public policy/descriptor**, persist it with the encrypted backup, and verify it during restore. This state model checks its format and equality only; it cannot prove the hash was derived correctly or that the descriptor is authentic. + +## What the state model enforces now + +- Enrollment and lost-phone recovery have separate state machines. Cloud unavailable, retry, decline, expiration, cancellation, and contact approval are explicit. +- A matching testnet preview cloud readback receipt is required before inviting or requesting a contact. It stores object references and digests, never ciphertext or private key material. +- The optional-code mode cannot request a contact until an external code verifier reports success. The code itself is never an event or state field. +- A contact response is tied to the active request, wallet policy hash, credential reference, replacement-device key reference, and expiry. Repeated responses cannot advance the state twice. +- Both flows stop at `awaiting-cryptographic-enrollment` or `awaiting-cryptographic-verification`. There is no “ready”, “recovered”, or funding state. + +## Required work before using this for funds + +1. Implement and review an authenticated Mobile Key backup format, key wrapping, nonce/replay handling, versioning, and recovery on a fresh device. Prefer standard reviewed protocols such as [HPKE (RFC 9180)](https://www.rfc-editor.org/rfc/rfc9180) for the contact key exchange; do not construct a custom ECDH protocol in the UI. +2. Provision isolated preview iCloud and Google Drive identities/containers. Add upload, download, authenticated readback, offline, interrupted-write, and restore APIs. Confirm the production Keeper namespace is inaccessible. +3. Build the contact app/device credential lifecycle: enrollment, public-key confirmation, secure storage, encrypted export/restore, rotation, revocation, and loss handling. Current address-book association is not a recovery credential. +4. Build a server-independent QR/share request and response channel with identity checks, approval and decline screens. Confirm the contact cannot silently approve a different wallet or replacement device. +5. Test two devices, both assurance modes, failed cloud readback, expired/replayed messages, lost contact credential, app reinstall, Keeper endpoints blocked, and exact recovered Mobile Key xpub. Obtain independent cryptographic/security review before labeling the path usable. + +The fixed Recovery Key-derived Mobile Key creates a separate Recovery Key restore route. If the Recovery Key is available, it can deterministically regenerate the same Mobile Key without contact approval; this contact route is meant for a lost phone when the user cannot or does not want to enter that Recovery Key. Neither route changes the wallet policy by itself. If a key is suspected compromised, rotation still requires a new policy, on-chain transfer, and Archived Wallet handling. diff --git a/src/components/WalletCreationChooser.tsx b/src/components/WalletCreationChooser.tsx new file mode 100644 index 000000000..35cd99890 --- /dev/null +++ b/src/components/WalletCreationChooser.tsx @@ -0,0 +1,246 @@ +import React from 'react'; +import { PixelRatio, Pressable, StyleSheet, View } from 'react-native'; +import { useColorMode } from '@gluestack-ui/themed-native-base'; +import Text from 'src/components/KeeperText'; +import Colors from 'src/theme/Colors'; + +type WalletChoiceCardProps = { + title: string; + icon: string; + description: string; + eyebrow?: string; + note?: string; + highlighted?: boolean; + testID: string; + onPress: () => void; +}; + +export type WalletCreationChooserProps = { + onSimpleWallet: () => void; + onSeedlessWallet?: () => void; + onAdvancedWallet: () => void; + onImportWallet?: () => void; + showSeedless?: boolean; + seedlessBadge?: string; + seedlessResumeHint?: string; + previewNotice?: string; +}; + +function ScaledText({ children, style, color, ...props }: any) { + const fontScale = Math.min(PixelRatio.getFontScale(), 2); + const textStyle = StyleSheet.flatten([styles.bodyText, style]); + return ( + + {children} + + ); +} + +export function WalletChoiceCard({ + title, + icon, + description, + eyebrow, + note, + highlighted = false, + testID, + onPress, +}: WalletChoiceCardProps) { + const { colorMode } = useColorMode(); + const dark = colorMode === 'dark'; + const accent = dark ? Colors.mintGreen : Colors.primaryGreen; + const text = dark ? Colors.bodyText : Colors.secondaryBlack; + + return ( + + + + + + {icon} + + + + {title} + + + › + + + {eyebrow && ( + + + {eyebrow} + + + )} + {description} + {note && ( + + {note} + + )} + + + ); +} + +export default function WalletCreationChooser({ + onSimpleWallet, + onSeedlessWallet, + onAdvancedWallet, + onImportWallet, + showSeedless = false, + seedlessBadge, + seedlessResumeHint, + previewNotice, +}: WalletCreationChooserProps) { + const { colorMode } = useColorMode(); + const dark = colorMode === 'dark'; + const accent = dark ? Colors.mintGreen : Colors.primaryGreen; + const muted = dark ? Colors.darkGrey : Colors.GreenishGrey; + + return ( + + + How would you like to hold your bitcoin? + + + {showSeedless && onSeedlessWallet && ( + <> + + {seedlessResumeHint && ( + + {seedlessResumeHint} + + )} + + )} + + {onImportWallet && ( + + Already have a wallet? + + + Import Wallet + + + + )} + {previewNotice && ( + + {previewNotice} + + )} + + ); +} + +const styles = StyleSheet.create({ + bodyText: { fontSize: 15, lineHeight: 23 }, + chooserSection: { gap: 14, paddingTop: 10 }, + chooserIntro: { marginBottom: 4 }, + choiceCard: { borderRadius: 16, padding: 16, gap: 9 }, + choiceHeader: { flexDirection: 'row', alignItems: 'center', gap: 11 }, + choiceIcon: { + width: 39, + height: 39, + borderRadius: 20, + alignItems: 'center', + justifyContent: 'center', + }, + choiceIconText: { fontSize: 21, lineHeight: 27, fontWeight: '600' }, + choiceTitle: { fontSize: 18, lineHeight: 25, fontWeight: '700', flex: 1 }, + choiceArrow: { fontSize: 29, lineHeight: 32 }, + choiceEyebrow: { fontSize: 12, lineHeight: 17, fontWeight: '600' }, + choiceBadge: { + alignSelf: 'flex-start', + borderRadius: 20, + paddingHorizontal: 11, + paddingVertical: 4, + }, + importRow: { + flexDirection: 'row', + flexWrap: 'wrap', + alignItems: 'center', + justifyContent: 'center', + marginTop: 14, + }, + importAction: { minHeight: 44, justifyContent: 'center', paddingHorizontal: 6 }, + importText: { fontWeight: '600' }, + resumeNote: { fontSize: 13, lineHeight: 20, marginTop: -3 }, + note: { fontSize: 13, lineHeight: 20 }, + previewNotice: { fontSize: 13, lineHeight: 20, textAlign: 'center' }, +}); diff --git a/src/navigation/Navigator.tsx b/src/navigation/Navigator.tsx index d5ecfc5bb..81cdfa642 100644 --- a/src/navigation/Navigator.tsx +++ b/src/navigation/Navigator.tsx @@ -76,6 +76,7 @@ import SatochipSeedImportModal from 'src/screens/SigningDevices/SatochipSeedImpo import PrivacyAndDisplay from 'src/screens/AppSettings/PrivacyAndDisplay'; import VaultConfigurationCreation from 'src/screens/Vault/VaultConfigurationRecreation'; import AddNewWallet from 'src/screens/AddWalletScreen/AddNewWallet'; +import WalletChoiceScreen from 'src/screens/AddWalletScreen/WalletChoiceScreen'; import ConfirmWalletDetails from 'src/screens/AddWalletScreen/ConfirmWalletDetails'; import HomeScreen from 'src/screens/Home/HomeScreen'; import ManageSigners from 'src/screens/SigningDevices/ManageSigners'; @@ -344,6 +345,7 @@ function AppStack() { + diff --git a/src/navigation/types.ts b/src/navigation/types.ts index 3f71fa080..54ae5209e 100644 --- a/src/navigation/types.ts +++ b/src/navigation/types.ts @@ -127,6 +127,7 @@ export type AppStackParams = { AssignSignerType: undefined; AddWallet: undefined; AddNewWallet: undefined; + WalletChoice: undefined; CanaryWallets: undefined; AssistedKeys: undefined; SafeKeepingTips: undefined; diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index 551a4ad86..a469df9a2 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -5,8 +5,17 @@ import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context'; import Text from 'src/components/KeeperText'; import ScreenWrapper from 'src/components/ScreenWrapper'; +import WalletCreationChooser, { WalletChoiceCard } from 'src/components/WalletCreationChooser'; import { customTheme } from 'src/navigation/themes'; import Colors from 'src/theme/Colors'; +import { + ContactDecisionState, + ContactEnrollmentState, + decideContactRequest, + initialContactEnrollment, + reduceContactEnrollment, + reviewContactRequest, +} from 'src/services/wallets/recoverable/contactRecoveryFlow'; import { HARDWARE_CHOICES, initialPreviewDraft, @@ -25,6 +34,30 @@ type Palette = { warning: string; }; +type PreviewSurface = + | 'wallets' + | 'chooser' + | 'simple' + | 'hot' + | 'cold' + | 'advanced' + | 'import' + | 'seedless' + | 'recovery' + | 'cloud' + | 'contact'; + +// Public placeholder metadata for an isolated UI sample. No wallet, policy, or credential exists. +const SAMPLE_POLICY_HASH = '0'.repeat(64); +const SAMPLE_NOW = 1_000_000; +const SAMPLE_REQUEST = { + requestId: 'sample-request-only', + walletPolicyHash: SAMPLE_POLICY_HASH, + contactCredentialId: 'sample-no-credential', + replacementDeviceKeyId: 'sample-no-device-key', + expiresAt: SAMPLE_NOW + 600, +}; + function PreviewText({ children, style, color, ...props }: any) { const fontScale = Math.min(PixelRatio.getFontScale(), 2); const textStyle = StyleSheet.flatten([styles.bodyText, style]); @@ -153,31 +186,78 @@ function PreviewContent() { accent: dark ? Colors.mintGreen : Colors.primaryGreen, warning: dark ? Colors.DeepCharcoalGreen : Colors.dullGreen, }; - const [inFlow, setInFlow] = useState(false); + const [surface, setSurface] = useState('wallets'); const [draft, setDraft] = useState(initialPreviewDraft); + const [contactEnrollment, setContactEnrollment] = + useState(initialContactEnrollment); + const [contactSample, setContactSample] = useState<'overview' | 'invitation' | 'request'>( + 'overview' + ); + const [invitationDecision, setInvitationDecision] = useState< + 'pending' | 'approval-intent' | 'declined' | 'expired' + >('pending'); + const [requestDecision, setRequestDecision] = useState(null); const scrollRef = useRef(null); const act = (action: PreviewAction) => setDraft((current) => reducePreviewDraft(current, action)); - const exitFlow = () => setInFlow(false); + const exitFlow = () => setSurface('chooser'); + const openRecoveryOptions = () => { + setContactEnrollment( + reduceContactEnrollment(initialContactEnrollment, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: SAMPLE_POLICY_HASH, + }) + ); + setContactSample('overview'); + setInvitationDecision('pending'); + setRequestDecision(null); + setSurface('recovery'); + }; + const startSampleInvitation = () => { + setInvitationDecision('pending'); + setContactSample('invitation'); + }; + const startSampleRequest = () => { + setRequestDecision(reviewContactRequest(SAMPLE_REQUEST, SAMPLE_NOW)); + setContactSample('request'); + }; + const decideSampleRequest = (decision: 'approve' | 'decline' | 'expire') => { + setRequestDecision((current) => + current + ? decideContactRequest( + current, + decision, + decision === 'expire' ? SAMPLE_REQUEST.expiresAt : SAMPLE_NOW + 1 + ) + : current + ); + }; const back = () => { - if (draft.stage === 'complete') { + if (surface === 'cloud' || surface === 'contact') setSurface('recovery'); + else if (surface === 'recovery') setSurface('seedless'); + else if (surface === 'chooser') setSurface('wallets'); + else if (surface === 'simple') setSurface('chooser'); + else if (surface === 'hot' || surface === 'cold') setSurface('simple'); + else if (surface === 'advanced' || surface === 'import') setSurface('chooser'); + else if (surface === 'seedless' && draft.stage === 'complete') { act({ type: 'RESET' }); exitFlow(); - } else if (draft.stage === 'automatic') exitFlow(); - else act({ type: 'BACK' }); + } else if (surface === 'seedless' && draft.stage === 'automatic') exitFlow(); + else if (surface === 'seedless') act({ type: 'BACK' }); }; useEffect(() => { const subscription = BackHandler.addEventListener('hardwareBackPress', () => { - if (!inFlow) return false; + if (surface === 'wallets') return false; back(); return true; }); return () => subscription.remove(); - }, [inFlow, draft.stage]); + }, [surface, draft.stage]); useEffect(() => { scrollRef.current?.scrollTo({ y: 0, animated: false }); - }, [inFlow, draft.stage]); + }, [surface, draft.stage]); const selectedDevice = HARDWARE_CHOICES.find(({ id }) => id === draft.hardware); const hasDraft = @@ -186,8 +266,30 @@ function PreviewContent() { return ( - - TESTNET PREVIEW · Simulated walkthrough. No wallet, key, address, cloud backup, or server - registration is created. - + {surface !== 'chooser' && ( + + TESTNET PREVIEW · Simulated walkthrough. No wallet, key, address, cloud backup, or + server registration is created. + + )} - {!inFlow && ( + {surface === 'wallets' && ( - Recoverable Wallet + No wallets yet - Explore a fixed 2-of-3 wallet with an automatic Mobile Key and Server Key, then choose - your Hardware Key. This preview cannot receive or send bitcoin. + Choose the wallet setup that suits you. Nothing has been created in this preview. - - - Recoverable Wallet · Preview - - - Choose hardware, consider an optional Inheritance Key, and review the complete - proposed policy. - - setInFlow(true)} + label="Add Wallet" + onPress={() => setSurface('chooser')} palette={palette} /> - {hasDraft && ( - { - act({ type: 'RESET' }); - setInFlow(true); - }} - /> - )} - Progress can be resumed while this preview stays open. It is cleared when the app - closes. + This preview starts without a Hot Wallet. It cannot receive or send bitcoin. + + + )} + + {surface === 'chooser' && ( + setSurface('simple')} + onSeedlessWallet={() => setSurface('seedless')} + onAdvancedWallet={() => setSurface('advanced')} + onImportWallet={() => setSurface('import')} + showSeedless + seedlessBadge="TESTNET PREVIEW" + previewNotice="Simulated choices only. No wallet, key, address, or backup is created in this testnet preview." + seedlessResumeHint={ + hasDraft + ? 'Your Seedless Wallet walkthrough will resume where you left off.' + : undefined + } + /> + )} + + {surface === 'simple' && ( + + + One key to spend + + + Choose where the key would be held. These are simulated choices in this isolated + preview; no wallet or key will be created. + + setSurface('hot')} + /> + setSurface('cold')} + /> + + )} + + {(surface === 'hot' || surface === 'cold') && ( + + + {surface === 'hot' ? 'Hot Wallet' : 'Cold Wallet'} + + + {surface === 'hot' + ? 'A Hot Wallet would use one key on this phone. No key is generated or stored here.' + : 'A Cold Wallet would use one external signing key. No device is connected or registered here.'} + + + SIMULATED CHOICE · Simple Wallet creation is not available in this preview. No wallet, + address, or backup exists. + + setSurface('chooser')} + /> + + )} + + {surface === 'advanced' && ( + + + Custom multisig + + + Advanced Wallet is for choosing your keys and spending rules, including Miniscript + options such as Inheritance Key, Emergency Key, and Wallet Timelock. + + PREVIEW ONLY · Advanced Wallet creation is not connected in this isolated app. No + policy, key, or wallet is created. + )} - {inFlow && draft.stage === 'automatic' && ( + {surface === 'import' && ( + + + Import Wallet + + + Import is available in standard Keeper. The isolated testnet preview does not read + existing wallets or import files. + + + UNAVAILABLE IN PREVIEW · No existing wallet or key was accessed. + + + )} + + {surface === 'seedless' && draft.stage === 'automatic' && ( Automatic Keys @@ -290,7 +471,7 @@ function PreviewContent() { )} - {inFlow && draft.stage === 'hardware' && ( + {surface === 'seedless' && draft.stage === 'hardware' && ( Choose Hardware @@ -331,7 +512,7 @@ function PreviewContent() { )} - {inFlow && draft.stage === 'connect' && ( + {surface === 'seedless' && draft.stage === 'connect' && ( Connect Hardware @@ -382,14 +563,14 @@ function PreviewContent() { )} - {inFlow && draft.stage === 'inheritance' && ( + {surface === 'seedless' && draft.stage === 'inheritance' && ( Inheritance Key - An Inheritance Key gives your chosen heir or trusted party a delayed access path, - based on the wallet rules you set. + Proposal, not configured: an Inheritance Key would give your heir a delayed path after + a fixed on-chain unlock date. Opening Keeper would not reset that date. {draft.inheritanceEnabled && ( - Selection is simulated. No heir, delay, Inheritance Key, or Miniscript policy is - configured here. + SIMULATED PROPOSAL · Your heir would need an Inheritance Key and a second signer + they can access without Server Key. Changing the unlock date would require a new + wallet and moving bitcoin. No heir, date, signer, or Miniscript policy is + configured. )} )} - {inFlow && draft.stage === 'review' && ( + {surface === 'seedless' && draft.stage === 'review' && ( Review Policy @@ -455,7 +638,7 @@ function PreviewContent() { {draft.inheritanceEnabled - ? 'After eligibility, an Inheritance Key and any eligible original signer would form the 2-of-4 spending path. The delay and Miniscript conditions are not configured in this preview.' + ? 'Proposed delayed path, not configured: after a fixed on-chain unlock date, your heir would use an Inheritance Key plus a designated second signer available without Server Key. Opening Keeper would not reset the date. Changing it would require a new wallet and moving bitcoin. No date, signer, or Miniscript policy exists in this preview.' : 'The proposed wallet has only the base 2-of-3 spending path.'} @@ -478,7 +661,7 @@ function PreviewContent() { )} - {inFlow && draft.stage === 'complete' && ( + {surface === 'seedless' && draft.stage === 'complete' && ( Walkthrough Complete @@ -491,13 +674,272 @@ function PreviewContent() { review. No key, hardware device, cloud service, or Keeper server was accessed. + act({ type: 'RESET' })} palette={palette} + testID="preview-start-again" /> )} + + {surface === 'recovery' && ( + + + Recovery Options + + + Explore proposed ways to restore this wallet's Mobile Key on another phone. These + paths are separate from Keeper Recovery Key restoration and do not change the wallet + policy. + + + SIMULATED · No Mobile Key, encrypted cloud blob, contact credential, or server + exchange exists. Neither option can restore or spend bitcoin. + + setSurface('cloud')} + > + + + Encrypted Cloud Backup + + + A separate encrypted Mobile Key backup would need upload, download, and verified + readback. None is configured here. + + + + setSurface('contact')} + > + + + Recovery Contact + + + A contact could approve a lost-phone request using a separate credential. Cloud + readback and cryptographic verification would still be required. + + + + + )} + + {surface === 'cloud' && ( + + + Encrypted Cloud Backup + + + + Unavailable · readback not verified + + + No encrypted Mobile Key was written or downloaded. No dedicated preview iCloud or + Google Drive container is connected. A matching download alone would not prove + authenticated decryption. + + + {contactEnrollment.stage === 'cloud-offline' ? ( + + SIMULATED OFFLINE · The cloud cannot be reached. An invitation or recovery request + cannot continue without the backup readback. No upload was attempted. + + ) : ( + + READBACK NOT VERIFIED · Backup and recovery are blocked until a real encrypted + write, download, and authenticated readback succeed. + + )} + {contactEnrollment.stage === 'cloud-offline' ? ( + + setContactEnrollment((current) => + reduceContactEnrollment(current, { type: 'RETRY_CLOUD' }) + ) + } + palette={palette} + /> + ) : ( + + setContactEnrollment((current) => + reduceContactEnrollment(current, { type: 'CLOUD_OFFLINE' }) + ) + } + palette={palette} + /> + )} + setSurface('recovery')} + palette={palette} + testID="preview-recovery-back" + /> + + )} + + {surface === 'contact' && ( + + + Recovery Contact + + + A contact is not an Inheritance Key or wallet signer. Contact approval would help + restore only the Mobile Key; another signer would still be needed to spend. + + + ENROLLMENT BLOCKED · Cloud readback is not verified. No invitation can be sent, no + contact credential exists, and no recovery request can be exchanged. + + {contactEnrollment.stage === 'cloud-offline' && ( + + SIMULATED OFFLINE · Cloud backup is unavailable. Contact recovery cannot proceed + without retrieving the encrypted backup. + + )} + {contactSample === 'overview' && ( + + + The samples below show possible decisions only. They do not bypass cloud readback + or create a contact credential. + + + + + )} + {contactSample === 'invitation' && ( + + + + Sample invitation · not sent + + + A real contact would review who invited them and decide whether to accept. No + invitation, contact credential, or wrapped backup key exists in this sample. + + + {invitationDecision === 'pending' ? ( + + setInvitationDecision('approval-intent')} + palette={palette} + /> + setInvitationDecision('declined')} + palette={palette} + testID="preview-invite-decline" + /> + setInvitationDecision('expired')} + palette={palette} + testID="preview-invite-expire" + /> + + ) : ( + + {invitationDecision === 'approval-intent' + ? 'SIMULATED APPROVAL INTENT · No credential was enrolled and no cryptographic key wrapping occurred.' + : invitationDecision === 'declined' + ? 'SIMULATED DECLINE · Enrollment stops. No credential or backup access was granted.' + : 'SIMULATED EXPIRY · The invitation can no longer be accepted. No credential was created.'} + + )} + + + + )} + {contactSample === 'request' && requestDecision && ( + + + + Sample lost-phone request · not sent + + + A contact would verify the person and replacement phone through a separate + trusted check before deciding. This sample has no enrolled credential, device + key, encrypted response, or server exchange. + + + {requestDecision.stage === 'pending' ? ( + + decideSampleRequest('approve')} + palette={palette} + /> + decideSampleRequest('decline')} + palette={palette} + testID="preview-request-decline" + /> + decideSampleRequest('expire')} + palette={palette} + testID="preview-request-expire" + /> + + ) : ( + + {requestDecision.stage === 'approval-intent' + ? 'SIMULATED APPROVAL INTENT · No response was encrypted or delivered, and no Mobile Key was restored.' + : requestDecision.stage === 'declined' + ? 'SIMULATED DECLINE · The recovery request stops. No Mobile Key was restored.' + : 'SIMULATED EXPIRY · The request cannot be approved. No Mobile Key was restored.'} + + )} + + + + )} + + )} ); diff --git a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx new file mode 100644 index 000000000..279d3ef16 --- /dev/null +++ b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx @@ -0,0 +1,127 @@ +import React, { useEffect, useState } from 'react'; +import { ScrollView, StyleSheet, View } from 'react-native'; +import { useColorMode } from '@gluestack-ui/themed-native-base'; +import { useNavigation } from '@react-navigation/native'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import ScreenWrapper from 'src/components/ScreenWrapper'; +import Text from 'src/components/KeeperText'; +import WalletHeader from 'src/components/WalletHeader'; +import WalletCreationChooser, { WalletChoiceCard } from 'src/components/WalletCreationChooser'; +import { useAppSelector } from 'src/store/hooks'; +import { NetworkType } from 'src/services/wallets/enums'; +import { isEmptyWalletOnboardingEnabled } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; + +type ChoiceStage = 'chooser' | 'simple' | 'hot' | 'cold' | 'seedless'; + +export default function WalletChoiceScreen() { + const navigation = useNavigation(); + const { colorMode } = useColorMode(); + const network = useAppSelector((state) => state.settings.bitcoinNetworkType); + const enabled = + network === NetworkType.TESTNET && + isEmptyWalletOnboardingEnabled({ + emptyWalletFlag: NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING, + previewFlag: NativeConfig.KEEPER_PREVIEW, + testnetOnlyFlag: NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY, + bundleId: DeviceInfo.getBundleId(), + }); + const [stage, setStage] = useState('chooser'); + + useEffect(() => { + if (!enabled) navigation.goBack(); + }, [enabled, navigation]); + + if (!enabled) return null; + + const back = () => { + if (stage === 'hot' || stage === 'cold') setStage('simple'); + else if (stage === 'simple' || stage === 'seedless') setStage('chooser'); + else navigation.goBack(); + }; + + const title = + stage === 'chooser' + ? 'Choose a Wallet' + : stage === 'simple' + ? 'Simple Wallet' + : stage === 'hot' + ? 'Hot Wallet' + : stage === 'cold' + ? 'Cold Wallet' + : 'Seedless Wallet'; + + return ( + + + + {stage === 'chooser' && ( + setStage('simple')} + onSeedlessWallet={() => setStage('seedless')} + onAdvancedWallet={() => navigation.navigate('AddNewWallet')} + onImportWallet={() => navigation.navigate('VaultConfigurationCreation')} + showSeedless + seedlessBadge="TESTNET PREVIEW" + /> + )} + {stage === 'simple' && ( + + + A Simple Wallet uses one key to spend. Choose where that key would be held. + + setStage('hot')} + /> + setStage('cold')} + /> + + )} + {/* TODO: Wire these choices after the empty-account Mobile Key readiness and cold signer + flows are verified end to end. Do not route to AddSigningDevice with a missing signer. */} + {(stage === 'hot' || stage === 'cold') && ( + + + {stage === 'hot' + ? 'Hot Wallet creation needs the Mobile Key to be ready before continuing.' + : 'Cold Wallet creation needs a supported signing device and a verified setup flow.'} + + + This route is not available in the testnet preview yet. No wallet or key has been + created. + + + )} + {/* The separately installed preview app owns the Seedless walkthrough. This normal-app + route must not mount its isolated provider tree or request a Server Key. */} + {stage === 'seedless' && ( + + + The Seedless Wallet walkthrough runs in the separate Keeper Preview app. + + + No Mobile Key, Server Key, hardware connection, or wallet is created from this screen. + + + )} + + + ); +} + +const styles = StyleSheet.create({ + content: { paddingBottom: 36 }, + section: { gap: 16, paddingTop: 18 }, + body: { fontSize: 15, lineHeight: 23 }, +}); diff --git a/src/screens/Home/components/Wallet/HomeWallet.tsx b/src/screens/Home/components/Wallet/HomeWallet.tsx index f277a0b79..ad111e1ff 100644 --- a/src/screens/Home/components/Wallet/HomeWallet.tsx +++ b/src/screens/Home/components/Wallet/HomeWallet.tsx @@ -1,7 +1,10 @@ import { Box, useColorMode, View } from '@gluestack-ui/themed-native-base'; import React, { useContext, useState, useEffect } from 'react'; import { FlatList, StyleSheet, TouchableOpacity } from 'react-native'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; import DashedCta from 'src/components/DashedCta'; +import Buttons from 'src/components/Buttons'; import WalletCard from './WalletCard'; import Colors from 'src/theme/Colors'; import useWallets from 'src/hooks/useWallets'; @@ -10,7 +13,8 @@ import { Wallet } from 'src/services/wallets/interfaces/wallet'; import { Vault } from 'src/services/wallets/interfaces/vault'; import useWalletAsset from 'src/hooks/useWalletAsset'; -import { EntityKind, VisibilityType, WalletType } from 'src/services/wallets/enums'; +import { EntityKind, NetworkType, VisibilityType, WalletType } from 'src/services/wallets/enums'; +import { isEmptyWalletOnboardingEnabled } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; import { useNavigation, useFocusEffect, CommonActions } from '@react-navigation/native'; import KeeperModal from 'src/components/KeeperModal'; import Text from 'src/components/KeeperText'; @@ -45,6 +49,7 @@ import TickIcon from 'src/assets/images/icon_tick.svg'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import Fab from 'src/components/Fab'; import AddIcon from 'src/assets/images/add_white.svg'; +import AddWalletIllustration from 'src/assets/images/addWallet_illustration.svg'; import { useUTXOSpendability } from 'src/hooks/useUTXOSpendability'; import { clearDustToast } from 'src/store/reducers/utxos'; @@ -139,6 +144,17 @@ const HomeWallet = () => { ...allVaults, ...usdtWallets, ].filter((item) => item !== null); + const usePreviewWalletChooser = + bitcoinNetworkType === NetworkType.TESTNET && + isEmptyWalletOnboardingEnabled({ + emptyWalletFlag: NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING, + previewFlag: NativeConfig.KEEPER_PREVIEW, + testnetOnlyFlag: NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY, + bundleId: DeviceInfo.getBundleId(), + }); + const showWalletEmptyState = usePreviewWalletChooser && allWallets.length === 0; + const openWalletChoice = () => + navigation.dispatch(CommonActions.navigate({ name: 'WalletChoice' })); const [isShowAmount, setIsShowAmount] = useState(false); const DashedCta_hexagonBackgroundColor = ThemedColor({ name: 'DashedCta_hexagonBackgroundColor', @@ -280,13 +296,29 @@ const HomeWallet = () => { return ( - } - onPress={() => setPickWalletType(true)} - /> + {!showWalletEmptyState && ( + } + onPress={() => (usePreviewWalletChooser ? openWalletChoice() : setPickWalletType(true))} + /> + )} + + + No wallets yet + + + Choose how you want to hold your bitcoin. A Hot Wallet has not been created. + + + + ) : null + } refreshControl={} keyExtractor={(item, index) => `${item.id || index}`} showsVerticalScrollIndicator={false} @@ -441,6 +473,14 @@ const styles = StyleSheet.create({ walletContainer: { gap: 15, }, + emptyWalletContainer: { + alignItems: 'center', + paddingTop: hp(30), + paddingHorizontal: wp(18), + gap: hp(14), + }, + emptyWalletTitle: { fontSize: 20, textAlign: 'center' }, + emptyWalletBody: { fontSize: 15, lineHeight: 23, textAlign: 'center' }, addWalletOptionsList: { gap: wp(15), marginBottom: hp(10), diff --git a/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts b/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts new file mode 100644 index 000000000..c29dd2561 --- /dev/null +++ b/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts @@ -0,0 +1,31 @@ +import { getPreviewRuntime } from 'src/preview/recoverable-wallet/previewRuntime'; + +export interface EmptyWalletOnboardingGate { + emptyWalletFlag?: string; + previewFlag?: string; + testnetOnlyFlag?: string; + bundleId: string; +} + +/** + * An absent flag preserves Keeper's existing default Mobile Wallet behavior. + * This branch can suppress that wallet only inside the separately installed, + * testnet-only preview identity. A later production rollout needs review. + */ +export const isEmptyWalletOnboardingEnabled = ({ + emptyWalletFlag, + previewFlag, + testnetOnlyFlag, + bundleId, +}: EmptyWalletOnboardingGate): boolean => + emptyWalletFlag === 'true' && + getPreviewRuntime(previewFlag, bundleId, testnetOnlyFlag) === 'preview'; + +export const shouldAutomaticallyCreateMobileWallet = (gate: EmptyWalletOnboardingGate): boolean => + !isEmptyWalletOnboardingEnabled(gate); + +export const shouldRestoreFallbackMobileWallet = ( + gate: EmptyWalletOnboardingGate, + hasWalletImages: boolean, + hasVaultImages: boolean +): boolean => shouldAutomaticallyCreateMobileWallet(gate) && !hasWalletImages && !hasVaultImages; diff --git a/src/services/wallets/operations/recoverable/mobileKey.ts b/src/services/wallets/operations/recoverable/mobileKey.ts new file mode 100644 index 000000000..d1798ec4d --- /dev/null +++ b/src/services/wallets/operations/recoverable/mobileKey.ts @@ -0,0 +1,75 @@ +import * as bip39 from 'bip39'; +import BIP32Factory from 'bip32'; +import * as bitcoinJS from 'bitcoinjs-lib'; +import BIP85 from '../BIP85'; +import ecc from '../taproot-utils/noble_ecc'; +import { + RECOVERABLE_MOBILE_KEY_INDEX_START, + RECOVERABLE_MOBILE_KEY_MAX_ORDINAL, + RECOVERABLE_MOBILE_KEY_VERSION, + RECOVERABLE_MOBILE_KEY_SIGNER_PATH, +} from './mobileKeyConstants'; + +export { + RECOVERABLE_MOBILE_KEY_INDEX_START, + RECOVERABLE_MOBILE_KEY_MAX_ORDINAL, + RECOVERABLE_MOBILE_KEY_VERSION, + RECOVERABLE_MOBILE_KEY_SIGNER_PATH, +} from './mobileKeyConstants'; + +const bip32 = BIP32Factory(ecc); + +export interface RecoverableMobileKeyPublic { + version: typeof RECOVERABLE_MOBILE_KEY_VERSION; + ordinal: number; + bip85Index: number; + bip85Path: string; + signerPath: typeof RECOVERABLE_MOBILE_KEY_SIGNER_PATH; + network: 'testnet'; + masterFingerprint: string; + xpub: string; +} + +/** Derive public signer details without returning or persisting the child words/private key. */ +export const deriveRecoverableMobileKeyPublic = async ( + recoveryKey: string, + ordinal: number +): Promise => { + if ( + !Number.isSafeInteger(ordinal) || + ordinal < 0 || + ordinal > RECOVERABLE_MOBILE_KEY_MAX_ORDINAL + ) { + throw new Error('Invalid Recoverable Wallet ordinal'); + } + + const normalizedRecoveryKey = + typeof recoveryKey === 'string' + ? recoveryKey.normalize('NFKD').trim().replace(/\s+/g, ' ').toLowerCase() + : ''; + if ( + normalizedRecoveryKey.split(' ').length !== 12 || + !bip39.validateMnemonic(normalizedRecoveryKey) + ) { + throw new Error('A valid 12-word Keeper Recovery Key is required'); + } + + const bip85Index = RECOVERABLE_MOBILE_KEY_INDEX_START + ordinal; + const bip85Path = `m/83696968'/39'/0'/12'/${bip85Index}'`; + const entropy = await BIP85.bip39MnemonicToEntropy(bip85Path, normalizedRecoveryKey); + const childMnemonic = BIP85.entropyToBIP39(entropy, 12); + const childSeed = await bip39.mnemonicToSeed(childMnemonic); + const root = bip32.fromSeed(childSeed, bitcoinJS.networks.testnet); + const signer = root.derivePath(RECOVERABLE_MOBILE_KEY_SIGNER_PATH); + + return { + version: RECOVERABLE_MOBILE_KEY_VERSION, + ordinal, + bip85Index, + bip85Path, + signerPath: RECOVERABLE_MOBILE_KEY_SIGNER_PATH, + network: 'testnet', + masterFingerprint: root.fingerprint.toString('hex').toUpperCase(), + xpub: signer.neutered().toBase58(), + }; +}; diff --git a/src/services/wallets/operations/recoverable/mobileKeyConstants.ts b/src/services/wallets/operations/recoverable/mobileKeyConstants.ts new file mode 100644 index 000000000..426a14c09 --- /dev/null +++ b/src/services/wallets/operations/recoverable/mobileKeyConstants.ts @@ -0,0 +1,10 @@ +/** + * BIP85 indexes 0–99 belong to Keeper hot wallets/MY_KEEPER signers, and + * 100–199 belong to USDT wallets. Keep this range exclusive to testnet + * Recoverable Wallet Mobile Keys, even when earlier wallets are deleted. + * A future mainnet scheme must receive its own namespace and version. + */ +export const RECOVERABLE_MOBILE_KEY_INDEX_START = 1_000_000; +export const RECOVERABLE_MOBILE_KEY_MAX_ORDINAL = 99_999; +export const RECOVERABLE_MOBILE_KEY_VERSION = 1 as const; +export const RECOVERABLE_MOBILE_KEY_SIGNER_PATH = "m/48'/1'/0'/2'"; diff --git a/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts b/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts new file mode 100644 index 000000000..321466676 --- /dev/null +++ b/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts @@ -0,0 +1,137 @@ +import { + RECOVERABLE_MOBILE_KEY_MAX_ORDINAL, + RECOVERABLE_MOBILE_KEY_VERSION, +} from './mobileKeyConstants'; + +export type MobileKeyReservationState = 'reserved' | 'active' | 'archived' | 'tombstone'; + +export interface MobileKeyOrdinalReservation { + /** Stable creation ID assigned before signer derivation; not the xpub-derived Vault ID. */ + walletId: string; + ordinal: number; + version: typeof RECOVERABLE_MOBILE_KEY_VERSION; + state: MobileKeyReservationState; +} + +/** Must include every historical reservation, including deleted wallets. */ +export interface MobileKeyOrdinalLedger { + complete: boolean; + /** Persisted high-water mark; -1 means no Mobile Key has ever been reserved. */ + highWaterOrdinal: number; + records: readonly MobileKeyOrdinalReservation[]; + /** Optional durable reservations whose wallet record is not available. */ + usedOrdinals?: readonly number[]; +} + +export type MobileKeyOrdinalRequest = + | { kind: 'create'; walletId: string } + | { kind: 'restore'; walletId: string }; + +export type MobileKeyOrdinalAllocation = + | { + kind: 'create'; + ordinal: number; + version: typeof RECOVERABLE_MOBILE_KEY_VERSION; + reservationToPersist: MobileKeyOrdinalReservation; + } + | { kind: 'restore'; ordinal: number; version: typeof RECOVERABLE_MOBILE_KEY_VERSION }; + +const isValidOrdinal = (ordinal: number): boolean => + Number.isSafeInteger(ordinal) && ordinal >= 0 && ordinal <= RECOVERABLE_MOBILE_KEY_MAX_ORDINAL; + +/** + * Propose a fresh ordinal from a complete, persisted reservation ledger. + * The caller must atomically persist reservationToPersist before deriving a + * new Mobile Key; this pure function does not reserve storage by itself. + */ +export const allocateRecoverableMobileKeyOrdinal = ( + ledger: MobileKeyOrdinalLedger, + request: MobileKeyOrdinalRequest +): MobileKeyOrdinalAllocation => { + if ( + !ledger || + ledger.complete !== true || + !Number.isSafeInteger(ledger.highWaterOrdinal) || + ledger.highWaterOrdinal < -1 || + ledger.highWaterOrdinal > RECOVERABLE_MOBILE_KEY_MAX_ORDINAL || + !Array.isArray(ledger.records) || + (ledger.usedOrdinals !== undefined && !Array.isArray(ledger.usedOrdinals)) + ) { + throw new Error('Complete Mobile Key reservation history is required'); + } + if ( + !request || + (request.kind !== 'create' && request.kind !== 'restore') || + typeof request.walletId !== 'string' || + request.walletId.trim() !== request.walletId || + !request.walletId + ) { + throw new Error('Stable wallet ID and allocation mode are required'); + } + + const byWalletId = new Map(); + const byOrdinal = new Map(); + const usedOrdinals = new Set(); + + for (const record of ledger.records) { + if ( + !record || + typeof record.walletId !== 'string' || + !record.walletId || + record.walletId.trim() !== record.walletId || + record.version !== RECOVERABLE_MOBILE_KEY_VERSION || + !['reserved', 'active', 'archived', 'tombstone'].includes(record.state) || + !isValidOrdinal(record.ordinal) || + record.ordinal > ledger.highWaterOrdinal || + byWalletId.has(record.walletId) || + byOrdinal.has(record.ordinal) + ) { + throw new Error('Ambiguous Mobile Key reservation history'); + } + byWalletId.set(record.walletId, record); + byOrdinal.set(record.ordinal, record.walletId); + usedOrdinals.add(record.ordinal); + } + + const explicitOrdinals = new Set(); + for (const ordinal of ledger.usedOrdinals || []) { + if ( + !isValidOrdinal(ordinal) || + ordinal > ledger.highWaterOrdinal || + explicitOrdinals.has(ordinal) + ) { + throw new Error('Ambiguous Mobile Key reservation history'); + } + explicitOrdinals.add(ordinal); + usedOrdinals.add(ordinal); + } + + for (let ordinal = 0; ordinal <= ledger.highWaterOrdinal; ordinal += 1) { + if (!usedOrdinals.has(ordinal)) { + throw new Error('Incomplete Mobile Key reservation history'); + } + } + + const prior = byWalletId.get(request.walletId); + if (request.kind === 'restore') { + if (!prior) throw new Error('Wallet Mobile Key reservation not found'); + return { kind: 'restore', ordinal: prior.ordinal, version: prior.version }; + } + if (prior) throw new Error('Wallet ID already has a Mobile Key reservation'); + if (ledger.highWaterOrdinal === RECOVERABLE_MOBILE_KEY_MAX_ORDINAL) { + throw new Error('Recoverable Mobile Key ordinal range exhausted'); + } + + const ordinal = ledger.highWaterOrdinal + 1; + return { + kind: 'create', + ordinal, + version: RECOVERABLE_MOBILE_KEY_VERSION, + reservationToPersist: { + walletId: request.walletId, + ordinal, + version: RECOVERABLE_MOBILE_KEY_VERSION, + state: 'reserved', + }, + }; +}; diff --git a/src/services/wallets/recoverable/contactRecoveryFlow.ts b/src/services/wallets/recoverable/contactRecoveryFlow.ts new file mode 100644 index 000000000..155be5c52 --- /dev/null +++ b/src/services/wallets/recoverable/contactRecoveryFlow.ts @@ -0,0 +1,444 @@ +import { NetworkType } from '../enums'; + +/** Logical namespace only. Native iCloud/Drive isolation remains to be implemented. */ +export const RECOVERABLE_PREVIEW_CLOUD_NAMESPACE = 'recoverable-wallet-preview-v1' as const; + +/** Product choice remains open; both modes are modeled without collecting a code. */ +export type ContactRecoveryAssurance = 'cloud-and-contact' | 'cloud-contact-and-code'; + +/** + * Metadata from a future encrypted cloud adapter. The reducer checks that a + * downloaded object matches the bytes written. It does not verify encryption. + */ +export interface EncryptedCloudReadbackReceipt { + kind: 'encrypted-mobile-key-readback-v1'; + network: NetworkType.TESTNET; + namespace: typeof RECOVERABLE_PREVIEW_CLOUD_NAMESPACE; + walletPolicyHash: string; + objectId: string; + writtenCiphertextSha256: string; + readCiphertextSha256: string; + checkedAt: number; +} + +export interface ContactExchangeRequest { + requestId: string; + walletPolicyHash: string; + contactCredentialId: string; + replacementDeviceKeyId: string; + expiresAt: number; +} + +/** Opaque public metadata only. The encrypted envelope and proof are verified elsewhere. */ +export interface ContactApprovalEnvelopeMetadata extends ContactExchangeRequest { + kind: 'contact-approval-envelope-v1'; + ciphertextSha256: string; +} + +export type EnrollmentStage = + | 'idle' + | 'awaiting-cloud-readback' + | 'cloud-offline' + | 'awaiting-contact-invitation' + | 'waiting-for-contact' + | 'awaiting-cryptographic-enrollment' + | 'declined' + | 'expired' + | 'cancelled'; + +export interface ContactEnrollmentState { + stage: EnrollmentStage; + assurance: ContactRecoveryAssurance | null; + walletPolicyHash: string | null; + readback: EncryptedCloudReadbackReceipt | null; + invitation: { id: string; expiresAt: number } | null; + contactCredentialId: string | null; +} + +export const initialContactEnrollment: ContactEnrollmentState = { + stage: 'idle', + assurance: null, + walletPolicyHash: null, + readback: null, + invitation: null, + contactCredentialId: null, +}; + +export type ContactEnrollmentAction = + | { type: 'START'; assurance: ContactRecoveryAssurance; walletPolicyHash: string } + | { type: 'CLOUD_OFFLINE' } + | { type: 'RETRY_CLOUD' } + | { type: 'CLOUD_READBACK'; receipt: EncryptedCloudReadbackReceipt } + | { type: 'INVITE'; invitationId: string; expiresAt: number; now: number } + | { type: 'CONTACT_ACCEPTED'; invitationId: string; contactCredentialId: string; now: number } + | { type: 'CONTACT_DECLINED'; invitationId: string; now: number } + | { type: 'EXPIRE'; now: number } + | { type: 'CANCEL' }; + +export type RecoveryStage = + | 'idle' + | 'awaiting-cloud-readback' + | 'cloud-offline' + | 'awaiting-code-verification' + | 'awaiting-contact-request' + | 'waiting-for-contact' + | 'awaiting-cryptographic-verification' + | 'declined' + | 'expired' + | 'cancelled'; + +export interface ContactRecoveryState { + stage: RecoveryStage; + assurance: ContactRecoveryAssurance | null; + walletPolicyHash: string | null; + contactCredentialId: string | null; + readback: EncryptedCloudReadbackReceipt | null; + codeVerified: boolean; + request: ContactExchangeRequest | null; + approval: ContactApprovalEnvelopeMetadata | null; +} + +export const initialContactRecovery: ContactRecoveryState = { + stage: 'idle', + assurance: null, + walletPolicyHash: null, + contactCredentialId: null, + readback: null, + codeVerified: false, + request: null, + approval: null, +}; + +export type ContactRecoveryAction = + | { + type: 'START'; + assurance: ContactRecoveryAssurance; + walletPolicyHash: string; + contactCredentialId: string; + } + | { type: 'CLOUD_OFFLINE' } + | { type: 'RETRY_CLOUD' } + | { type: 'CLOUD_READBACK'; receipt: EncryptedCloudReadbackReceipt } + | { type: 'CODE_VERIFIED' } + | { type: 'REQUEST_CONTACT'; request: ContactExchangeRequest; now: number } + | { type: 'APPROVAL_RECEIVED'; envelope: ContactApprovalEnvelopeMetadata; now: number } + | { type: 'CONTACT_DECLINED'; requestId: string; now: number } + | { type: 'EXPIRE'; now: number } + | { type: 'CANCEL' }; + +export class ContactRecoveryFlowError extends Error { + constructor(public readonly code: string, message: string) { + super(message); + this.name = 'ContactRecoveryFlowError'; + } +} + +function fail(code: string, message: string): never { + throw new ContactRecoveryFlowError(code, message); +} + +function requireStage(actual: string, allowed: readonly string[]): void { + if (!allowed.includes(actual)) fail('INVALID_TRANSITION', `Action unavailable from ${actual}`); +} + +function requireId(value: unknown, field: string): string { + if (typeof value !== 'string' || !/^[A-Za-z0-9:_-]{1,128}$/.test(value)) { + fail('INVALID_REFERENCE', `${field} must be a public opaque identifier`); + } + return value; +} + +function requirePolicyHash(value: unknown): string { + if (typeof value !== 'string' || !/^[A-Fa-f0-9]{64}$/.test(value)) { + fail('INVALID_POLICY_HASH', 'Wallet policy hash must be 32 bytes in hexadecimal'); + } + return value.toUpperCase(); +} + +function requireNow(now: number): void { + if (!Number.isSafeInteger(now) || now <= 0) + fail('INVALID_TIME', 'A valid current time is required'); +} + +function requireAssurance(mode: ContactRecoveryAssurance): ContactRecoveryAssurance { + if (mode !== 'cloud-and-contact' && mode !== 'cloud-contact-and-code') { + fail('INVALID_ASSURANCE', 'Unsupported Recovery Contact assurance mode'); + } + return mode; +} + +function validateReadback( + receipt: EncryptedCloudReadbackReceipt, + expectedWalletPolicyHash: string +): EncryptedCloudReadbackReceipt { + if ( + !receipt || + receipt.kind !== 'encrypted-mobile-key-readback-v1' || + receipt.network !== NetworkType.TESTNET || + receipt.namespace !== RECOVERABLE_PREVIEW_CLOUD_NAMESPACE || + requirePolicyHash(receipt.walletPolicyHash) !== expectedWalletPolicyHash + ) { + fail('INVALID_READBACK', 'Readback does not belong to this testnet preview wallet'); + } + const objectId = requireId(receipt.objectId, 'Cloud object'); + if ( + !/^[a-fA-F0-9]{64}$/.test(receipt.writtenCiphertextSha256) || + !/^[a-fA-F0-9]{64}$/.test(receipt.readCiphertextSha256) || + receipt.writtenCiphertextSha256.toLowerCase() !== receipt.readCiphertextSha256.toLowerCase() || + !Number.isSafeInteger(receipt.checkedAt) || + receipt.checkedAt <= 0 + ) { + fail('READBACK_MISMATCH', 'Encrypted cloud payload was not read back unchanged'); + } + return { + kind: 'encrypted-mobile-key-readback-v1', + network: NetworkType.TESTNET, + namespace: RECOVERABLE_PREVIEW_CLOUD_NAMESPACE, + walletPolicyHash: expectedWalletPolicyHash, + objectId, + writtenCiphertextSha256: receipt.writtenCiphertextSha256.toLowerCase(), + readCiphertextSha256: receipt.readCiphertextSha256.toLowerCase(), + checkedAt: receipt.checkedAt, + }; +} + +function validateRequest( + request: ContactExchangeRequest, + walletPolicyHash: string, + contactCredentialId: string, + now: number +): ContactExchangeRequest { + requireNow(now); + if ( + !request || + requirePolicyHash(request.walletPolicyHash) !== walletPolicyHash || + requireId(request.contactCredentialId, 'Contact credential') !== contactCredentialId || + !Number.isSafeInteger(request.expiresAt) || + request.expiresAt <= now + ) { + fail('INVALID_REQUEST', 'Recovery Contact request does not match this wallet or has expired'); + } + return { + requestId: requireId(request.requestId, 'Request'), + walletPolicyHash, + contactCredentialId, + replacementDeviceKeyId: requireId(request.replacementDeviceKeyId, 'Replacement device key'), + expiresAt: request.expiresAt, + }; +} + +function requireActiveInvitation( + invitation: NonNullable, + invitationId: string, + now: number +) { + requireNow(now); + if (invitation.id !== invitationId) fail('REQUEST_MISMATCH', 'Invitation does not match'); + if (now >= invitation.expiresAt) fail('REQUEST_EXPIRED', 'Invitation has expired'); +} + +function requireActiveRequest(request: ContactExchangeRequest, requestId: string, now: number) { + requireNow(now); + if (request.requestId !== requestId) fail('REQUEST_MISMATCH', 'Request does not match'); + if (now >= request.expiresAt) fail('REQUEST_EXPIRED', 'Request has expired'); +} + +/** State only; accepting a contact does not yet prove a wrapped key is usable. */ +export function reduceContactEnrollment( + state: ContactEnrollmentState, + action: ContactEnrollmentAction +): ContactEnrollmentState { + switch (action.type) { + case 'START': + requireStage(state.stage, ['idle', 'declined', 'expired', 'cancelled']); + return { + ...initialContactEnrollment, + stage: 'awaiting-cloud-readback', + assurance: requireAssurance(action.assurance), + walletPolicyHash: requirePolicyHash(action.walletPolicyHash), + }; + case 'CLOUD_OFFLINE': + requireStage(state.stage, ['awaiting-cloud-readback']); + return { ...state, stage: 'cloud-offline' }; + case 'RETRY_CLOUD': + requireStage(state.stage, ['cloud-offline']); + return { ...state, stage: 'awaiting-cloud-readback' }; + case 'CLOUD_READBACK': + requireStage(state.stage, ['awaiting-cloud-readback']); + return { + ...state, + stage: 'awaiting-contact-invitation', + readback: validateReadback(action.receipt, state.walletPolicyHash!), + }; + case 'INVITE': + requireStage(state.stage, ['awaiting-contact-invitation']); + requireNow(action.now); + if (!Number.isSafeInteger(action.expiresAt) || action.expiresAt <= action.now) { + fail('INVALID_TIME', 'Contact invitation must expire in the future'); + } + return { + ...state, + stage: 'waiting-for-contact', + invitation: { + id: requireId(action.invitationId, 'Invitation'), + expiresAt: action.expiresAt, + }, + }; + case 'CONTACT_ACCEPTED': + requireStage(state.stage, ['waiting-for-contact']); + requireActiveInvitation(state.invitation!, action.invitationId, action.now); + return { + ...state, + stage: 'awaiting-cryptographic-enrollment', + contactCredentialId: requireId(action.contactCredentialId, 'Contact credential'), + }; + case 'CONTACT_DECLINED': + requireStage(state.stage, ['waiting-for-contact']); + requireActiveInvitation(state.invitation!, action.invitationId, action.now); + return { ...state, stage: 'declined' }; + case 'EXPIRE': + requireStage(state.stage, ['waiting-for-contact']); + requireNow(action.now); + return action.now >= state.invitation!.expiresAt ? { ...state, stage: 'expired' } : state; + case 'CANCEL': + requireStage(state.stage, [ + 'awaiting-cloud-readback', + 'cloud-offline', + 'awaiting-contact-invitation', + 'waiting-for-contact', + 'awaiting-cryptographic-enrollment', + ]); + return { ...state, stage: 'cancelled' }; + } +} + +/** State only; no action in this reducer decrypts or reconstructs a Mobile Key. */ +export function reduceContactRecovery( + state: ContactRecoveryState, + action: ContactRecoveryAction +): ContactRecoveryState { + switch (action.type) { + case 'START': + requireStage(state.stage, ['idle', 'declined', 'expired', 'cancelled']); + return { + ...initialContactRecovery, + stage: 'awaiting-cloud-readback', + assurance: requireAssurance(action.assurance), + walletPolicyHash: requirePolicyHash(action.walletPolicyHash), + contactCredentialId: requireId(action.contactCredentialId, 'Contact credential'), + }; + case 'CLOUD_OFFLINE': + requireStage(state.stage, ['awaiting-cloud-readback']); + return { ...state, stage: 'cloud-offline' }; + case 'RETRY_CLOUD': + requireStage(state.stage, ['cloud-offline']); + return { ...state, stage: 'awaiting-cloud-readback' }; + case 'CLOUD_READBACK': + requireStage(state.stage, ['awaiting-cloud-readback']); + return { + ...state, + stage: + state.assurance === 'cloud-contact-and-code' + ? 'awaiting-code-verification' + : 'awaiting-contact-request', + readback: validateReadback(action.receipt, state.walletPolicyHash!), + }; + case 'CODE_VERIFIED': + requireStage(state.stage, ['awaiting-code-verification']); + return { ...state, stage: 'awaiting-contact-request', codeVerified: true }; + case 'REQUEST_CONTACT': + requireStage(state.stage, ['awaiting-contact-request']); + if ( + !state.readback || + (state.assurance === 'cloud-contact-and-code' && !state.codeVerified) + ) { + fail('PREREQUISITE_MISSING', 'Cloud readback and required code check must finish first'); + } + return { + ...state, + stage: 'waiting-for-contact', + request: validateRequest( + action.request, + state.walletPolicyHash!, + state.contactCredentialId!, + action.now + ), + }; + case 'APPROVAL_RECEIVED': { + requireStage(state.stage, ['waiting-for-contact']); + const request = state.request!; + requireActiveRequest(request, action.envelope?.requestId, action.now); + if ( + action.envelope.kind !== 'contact-approval-envelope-v1' || + requirePolicyHash(action.envelope.walletPolicyHash) !== request.walletPolicyHash || + action.envelope.contactCredentialId !== request.contactCredentialId || + action.envelope.replacementDeviceKeyId !== request.replacementDeviceKeyId || + action.envelope.expiresAt !== request.expiresAt || + !/^[a-fA-F0-9]{64}$/.test(action.envelope.ciphertextSha256) + ) { + fail('ENVELOPE_MISMATCH', 'Contact response is not bound to this request and device'); + } + return { + ...state, + stage: 'awaiting-cryptographic-verification', + approval: { + ...request, + kind: 'contact-approval-envelope-v1', + ciphertextSha256: action.envelope.ciphertextSha256.toLowerCase(), + }, + }; + } + case 'CONTACT_DECLINED': + requireStage(state.stage, ['waiting-for-contact']); + requireActiveRequest(state.request!, action.requestId, action.now); + return { ...state, stage: 'declined' }; + case 'EXPIRE': + requireStage(state.stage, ['waiting-for-contact']); + requireNow(action.now); + return action.now >= state.request!.expiresAt ? { ...state, stage: 'expired' } : state; + case 'CANCEL': + requireStage(state.stage, [ + 'awaiting-cloud-readback', + 'cloud-offline', + 'awaiting-code-verification', + 'awaiting-contact-request', + 'waiting-for-contact', + 'awaiting-cryptographic-verification', + ]); + return { ...state, stage: 'cancelled' }; + } +} + +export type ContactDecisionState = + | { stage: 'pending'; request: ContactExchangeRequest } + | { stage: 'approval-intent'; request: ContactExchangeRequest } + | { stage: 'declined'; request: ContactExchangeRequest } + | { stage: 'expired'; request: ContactExchangeRequest }; + +export function reviewContactRequest( + request: ContactExchangeRequest, + now: number +): ContactDecisionState { + const validated = validateRequest( + request, + requirePolicyHash(request.walletPolicyHash), + request.contactCredentialId, + now + ); + return { stage: 'pending', request: validated }; +} + +/** Approval intent still needs an independent, authenticated encryption channel. */ +export function decideContactRequest( + state: ContactDecisionState, + decision: 'approve' | 'decline' | 'expire', + now: number +): ContactDecisionState { + requireStage(state.stage, ['pending']); + requireNow(now); + if (now >= state.request.expiresAt) return { ...state, stage: 'expired' }; + if (decision === 'approve') return { ...state, stage: 'approval-intent' }; + if (decision === 'decline') return { ...state, stage: 'declined' }; + if (decision === 'expire') return state; + return fail('INVALID_DECISION', 'Unknown contact decision'); +} diff --git a/src/services/wallets/recoverable/policyDraft.ts b/src/services/wallets/recoverable/policyDraft.ts new file mode 100644 index 000000000..d5483b19e --- /dev/null +++ b/src/services/wallets/recoverable/policyDraft.ts @@ -0,0 +1,488 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import { MultisigScriptType, NetworkType, SignerType } from '../enums'; +import type { MiniscriptElements, VaultScheme } from '../interfaces/vault'; +import { generateMiniscript } from '../operations/miniscript/miniscript'; +import { + generateMiniscriptPolicy, + KeyInfo, + Phase, +} from '../operations/miniscript/policy-generator'; +import ecc from '../operations/taproot-utils/noble_ecc'; + +const bip32 = BIP32Factory(ecc); + +/** The draft never contains private keys or authorizes creation of a funded wallet. */ +export const RECOVERABLE_POLICY_DRAFT_VERSION = 1 as const; +const MOBILE_KEY_BIP85_START = 1_000_000; +const MOBILE_KEY_MAX_ORDINAL = 99_999; +const MOBILE_KEY_SIGNER_PATH = "m/48'/1'/0'/2'"; +const MAX_LOCKTIME = 0xffffffff; + +export type RecoverableHardware = + | SignerType.TAPSIGNER + | SignerType.SATOCHIP + | SignerType.JADE + | SignerType.COLDCARD; + +export type HardwareTransport = 'nfc' | 'qr' | 'file' | 'desktop-usb'; + +export type RecoverableSignerRole = 'mobile' | 'hardware' | 'server' | 'inheritance'; + +export interface RecoverablePublicSignerBase { + role: RecoverableSignerRole; + signerType: SignerType; + masterFingerprint: string; + /** Account-level BIP48 testnet extended PUBLIC key. */ + xpub: string; + /** Origin of xpub, e.g. m/48'/1'/0'/2'. Never the BIP85 child path. */ + derivationPath: string; +} + +export interface RecoverableMobileSigner extends RecoverablePublicSignerBase { + role: 'mobile'; + signerType: SignerType.MOBILE_KEY; + origin: { + kind: 'keeper-recovery-key-bip85'; + version: 1; + ordinal: number; + bip85Index: number; + bip85Path: string; + }; +} + +export interface RecoverableHardwareSigner extends RecoverablePublicSignerBase { + role: 'hardware'; + signerType: RecoverableHardware; + origin: { + kind: 'hardware-device'; + device: RecoverableHardware; + transport: HardwareTransport; + /** A public import reference, not a device secret. */ + sourceId: string; + }; +} + +export interface RecoverableServerSigner extends RecoverablePublicSignerBase { + role: 'server'; + signerType: SignerType.POLICY_SERVER; + origin: { + kind: 'keeper-server-key'; + /** Public correlation only; this draft does not register or request a key. */ + sourceId: string; + }; +} + +export interface RecoverableInheritanceSigner extends RecoverablePublicSignerBase { + role: 'inheritance'; + origin: { + kind: 'externally-held-inheritance-key'; + /** Public correlation only; no contact identity or private material is stored here. */ + sourceId: string; + }; +} + +export interface RecoverableInheritanceChoice { + signer: RecoverableInheritanceSigner; + activation: { + kind: 'block-height' | 'median-time-past'; + /** Absolute Bitcoin locktime chosen before the whole-policy review. */ + value: number; + /** Chain observation supplied by the caller; this module performs no network request. */ + observedHeight: number; + observedMedianTimePast: number; + }; +} + +export interface RecoverablePolicyDraftInput { + version: typeof RECOVERABLE_POLICY_DRAFT_VERSION; + network: NetworkType.TESTNET; + mobile: RecoverableMobileSigner; + hardware: RecoverableHardwareSigner; + server: RecoverableServerSigner; + inheritance?: RecoverableInheritanceChoice | null; +} + +export interface RecoverablePolicyReview { + kind: 'public-policy-review'; + version: typeof RECOVERABLE_POLICY_DRAFT_VERSION; + network: NetworkType.TESTNET; + /** Fixed Mobile + Hardware + Server quorum. */ + base: { + required: 2; + total: 3; + signers: readonly [RecoverableMobileSigner, RecoverableHardwareSigner, RecoverableServerSigner]; + }; + inheritance: null | { + required: 2; + total: 4; + signer: RecoverableInheritanceSigner; + activation: RecoverableInheritanceChoice['activation']; + }; + /** Matches Keeper's plain 2-of-3 Vault scheme only when inheritance is absent. */ + baseVaultScheme: VaultScheme | null; + /** Compiled public script for review only; this is deliberately not a fundable VaultScheme. */ + candidateMiniscript: null | { + policy: string; + miniscript: string; + phases: readonly { timelock: number; signerCount: number; required: 2 }[]; + }; + hardwarePolicyStatus: 'plain-multisig-not-device-tested' | 'inheritance-policy-not-device-tested'; + /** Every draft stays blocked from funding, registration and signing. */ + fundable: false; +} + +export class RecoverablePolicyDraftError extends Error { + constructor(public readonly code: string, message: string) { + super(message); + this.name = 'RecoverablePolicyDraftError'; + } +} + +const hardwareTransports: Record = { + [SignerType.TAPSIGNER]: ['nfc'], + [SignerType.SATOCHIP]: ['nfc'], + [SignerType.JADE]: ['qr', 'desktop-usb'], + [SignerType.COLDCARD]: ['qr', 'file', 'nfc', 'desktop-usb'], +}; + +function fail(code: string, message: string): never { + throw new RecoverablePolicyDraftError(code, message); +} + +function nonEmptyPublicId(value: unknown, field: string): string { + if (typeof value !== 'string' || !value.trim() || value.length > 256) { + fail('INVALID_ORIGIN', `${field} must be a non-empty public reference`); + } + return value.trim(); +} + +function assertOnlyKeys(value: object, allowed: readonly string[], field: string): void { + for (const key of Object.keys(value)) { + if (['xpriv', 'mnemonic', 'seed', 'recoveryKey'].includes(key)) { + fail('PRIVATE_MATERIAL', `${field} must not contain private key material`); + } + if (!allowed.includes(key)) fail('UNEXPECTED_FIELD', `${field} contains an unexpected field`); + } +} + +function normalizePublicSigner( + signer: T, + role: T['role'] +): T { + if (!signer || signer.role !== role) fail('INVALID_ROLE', `Expected ${role} signer`); + assertOnlyKeys( + signer, + ['role', 'signerType', 'masterFingerprint', 'xpub', 'derivationPath', 'origin'], + role + ); + const fingerprint = + typeof signer.masterFingerprint === 'string' ? signer.masterFingerprint.toUpperCase() : ''; + if (!/^[0-9A-F]{8}$/.test(fingerprint || '')) { + fail('INVALID_FINGERPRINT', `Invalid ${role} master fingerprint`); + } + if ( + typeof signer.derivationPath !== 'string' || + !/^m\/48'\/1'\/(0|[1-9]\d*)'\/2'$/.test(signer.derivationPath) + ) { + fail('INVALID_DERIVATION', `${role} must use a testnet BIP48 native-segwit origin`); + } + const account = Number(signer.derivationPath.split('/')[3].replace("'", '')); + if (!Number.isSafeInteger(account) || account > 0x7fffffff) { + fail('INVALID_DERIVATION', `${role} account is out of range`); + } + try { + const node = bip32.fromBase58(signer.xpub, bitcoin.networks.testnet); + if (!node.isNeutered()) fail('PRIVATE_MATERIAL', 'Only public extended keys are allowed'); + // A tpub cannot prove its full ancestor path or claimed master fingerprint, + // but its serialized depth and final hardened child index must match BIP48. + if (node.depth !== 4 || node.index !== 0x80000002) { + fail('INVALID_XPUB_ORIGIN', `${role} must be an account-level BIP48 native-segwit tpub`); + } + } catch (error) { + if (error instanceof RecoverablePolicyDraftError) throw error; + fail('INVALID_XPUB', `${role} must provide a valid testnet public extended key`); + } + return { ...signer, masterFingerprint: fingerprint }; +} + +function validateMobile(signer: RecoverableMobileSigner): RecoverableMobileSigner { + const normalized = normalizePublicSigner(signer, 'mobile'); + if (normalized.origin && typeof normalized.origin === 'object') { + assertOnlyKeys( + normalized.origin, + ['kind', 'version', 'ordinal', 'bip85Index', 'bip85Path'], + 'Mobile origin' + ); + } + if ( + normalized.signerType !== SignerType.MOBILE_KEY || + normalized.derivationPath !== MOBILE_KEY_SIGNER_PATH || + normalized.origin?.kind !== 'keeper-recovery-key-bip85' || + normalized.origin.version !== 1 + ) { + fail('INVALID_MOBILE_ORIGIN', 'Mobile Key must use the version 1 Recovery Key derivation'); + } + const { ordinal, bip85Index, bip85Path } = normalized.origin; + if ( + !Number.isSafeInteger(ordinal) || + ordinal < 0 || + ordinal > MOBILE_KEY_MAX_ORDINAL || + bip85Index !== MOBILE_KEY_BIP85_START + ordinal || + bip85Path !== `m/83696968'/39'/0'/12'/${bip85Index}'` + ) { + fail('INVALID_MOBILE_ORIGIN', 'Mobile Key BIP85 metadata does not match its ordinal'); + } + return { + role: 'mobile', + signerType: SignerType.MOBILE_KEY, + masterFingerprint: normalized.masterFingerprint, + xpub: normalized.xpub, + derivationPath: normalized.derivationPath, + origin: { kind: 'keeper-recovery-key-bip85', version: 1, ordinal, bip85Index, bip85Path }, + }; +} + +function validateHardware(signer: RecoverableHardwareSigner): RecoverableHardwareSigner { + const normalized = normalizePublicSigner(signer, 'hardware'); + if (normalized.origin && typeof normalized.origin === 'object') { + assertOnlyKeys( + normalized.origin, + ['kind', 'device', 'transport', 'sourceId'], + 'Hardware origin' + ); + } + const transports = hardwareTransports[normalized.signerType]; + if ( + !transports || + normalized.origin?.kind !== 'hardware-device' || + normalized.origin.device !== normalized.signerType || + !transports.includes(normalized.origin.transport) + ) { + fail('UNSUPPORTED_HARDWARE', 'Hardware type or import transport is unsupported'); + } + return { + role: 'hardware', + signerType: normalized.signerType, + masterFingerprint: normalized.masterFingerprint, + xpub: normalized.xpub, + derivationPath: normalized.derivationPath, + origin: { + kind: 'hardware-device', + device: normalized.signerType, + transport: normalized.origin.transport, + sourceId: nonEmptyPublicId(normalized.origin.sourceId, 'Hardware source'), + }, + }; +} + +function validateServer(signer: RecoverableServerSigner): RecoverableServerSigner { + const normalized = normalizePublicSigner(signer, 'server'); + if (normalized.origin && typeof normalized.origin === 'object') { + assertOnlyKeys(normalized.origin, ['kind', 'sourceId'], 'Server origin'); + } + if ( + normalized.signerType !== SignerType.POLICY_SERVER || + normalized.origin?.kind !== 'keeper-server-key' + ) { + fail('INVALID_SERVER_ORIGIN', 'Server Key requires distinct server-issued public material'); + } + return { + role: 'server', + signerType: SignerType.POLICY_SERVER, + masterFingerprint: normalized.masterFingerprint, + xpub: normalized.xpub, + derivationPath: normalized.derivationPath, + origin: { + kind: 'keeper-server-key', + sourceId: nonEmptyPublicId(normalized.origin.sourceId, 'Server source'), + }, + }; +} + +function validateInheritance(choice: RecoverableInheritanceChoice): RecoverableInheritanceChoice { + if (choice && typeof choice === 'object') { + assertOnlyKeys(choice, ['signer', 'activation'], 'Inheritance choice'); + } + const signer = normalizePublicSigner(choice?.signer, 'inheritance'); + if (signer.origin && typeof signer.origin === 'object') { + assertOnlyKeys(signer.origin, ['kind', 'sourceId'], 'Inheritance origin'); + } + if ( + signer.origin?.kind !== 'externally-held-inheritance-key' || + signer.signerType === SignerType.POLICY_SERVER || + signer.signerType === SignerType.MOBILE_KEY + ) { + fail('INVALID_INHERITANCE_ORIGIN', 'Inheritance Key must be independently held'); + } + const activation = choice?.activation; + if (activation && typeof activation === 'object') { + assertOnlyKeys( + activation, + ['kind', 'value', 'observedHeight', 'observedMedianTimePast'], + 'Inheritance activation' + ); + } + if ( + !activation || + !Number.isSafeInteger(activation.value) || + !Number.isSafeInteger(activation.observedHeight) || + !Number.isSafeInteger(activation.observedMedianTimePast) || + activation.observedHeight < 0 || + activation.observedMedianTimePast < 500000000 + ) { + fail( + 'INVALID_ACTIVATION', + 'Inheritance requires a valid chain observation and absolute locktime' + ); + } + if (activation.kind === 'block-height') { + if (activation.value <= activation.observedHeight || activation.value >= 500000000) { + fail('INVALID_ACTIVATION', 'Inheritance block height must be in the future'); + } + } else if (activation.kind === 'median-time-past') { + if (activation.value <= activation.observedMedianTimePast || activation.value > MAX_LOCKTIME) { + fail('INVALID_ACTIVATION', 'Inheritance median time past must be in the future'); + } + } else { + fail('INVALID_ACTIVATION', 'Unsupported inheritance locktime kind'); + } + return { + signer: { + role: 'inheritance', + signerType: signer.signerType, + masterFingerprint: signer.masterFingerprint, + xpub: signer.xpub, + derivationPath: signer.derivationPath, + origin: { + kind: 'externally-held-inheritance-key', + sourceId: nonEmptyPublicId(signer.origin.sourceId, 'Inheritance source'), + }, + }, + activation: { + kind: activation.kind, + value: activation.value, + observedHeight: activation.observedHeight, + observedMedianTimePast: activation.observedMedianTimePast, + }, + }; +} + +function assertDistinctSigners(signers: RecoverablePublicSignerBase[]) { + const fingerprints = new Set(); + const xpubs = new Set(); + for (const signer of signers) { + if (fingerprints.has(signer.masterFingerprint) || xpubs.has(signer.xpub)) { + fail('DUPLICATE_KEY', 'Each policy role must have independent key material'); + } + fingerprints.add(signer.masterFingerprint); + xpubs.add(signer.xpub); + } +} + +function asKeyInfo(signer: RecoverablePublicSignerBase, identifier: string): KeyInfo { + const origin = signer.derivationPath.substring(2).replace(/'/g, 'h'); + return { + identifier, + descriptor: `[${signer.masterFingerprint}/${origin}]${signer.xpub}`, + }; +} + +function compileInheritanceCandidate( + signers: readonly [RecoverableMobileSigner, RecoverableHardwareSigner, RecoverableServerSigner], + inheritance: RecoverableInheritanceChoice +): NonNullable { + const baseKeys = signers.map((signer, index) => asKeyInfo(signer, `K${index + 1}`)); + const inheritanceKey = asKeyInfo(inheritance.signer, 'IK1'); + const phases: Phase[] = [ + { + id: 1, + timelock: 0, + requiredPaths: 1, + probability: 9, + paths: [{ id: 1, threshold: 2, keys: baseKeys }], + }, + { + id: 2, + timelock: inheritance.activation.value, + requiredPaths: 1, + probability: 1, + paths: [{ id: 1, threshold: 2, keys: [...baseKeys, inheritanceKey] }], + }, + ]; + const elements: MiniscriptElements = { + keysInfo: [...baseKeys, inheritanceKey], + timelocks: [inheritance.activation.value], + phases, + signerFingerprints: Object.fromEntries( + [...baseKeys, inheritanceKey].map((key) => [key.identifier, key.descriptor.substring(1, 9)]) + ), + }; + const { miniscriptPhases, policy } = generateMiniscriptPolicy(elements); + const { miniscript } = generateMiniscript(policy); + // The compiler output is intentionally reduced to review data. The key map and + // MiniscriptScheme required for a real Vault must be assembled after hardware proof. + return { + policy, + miniscript, + phases: miniscriptPhases.map((phase) => ({ + timelock: phase.timelock, + signerCount: phase.paths[0].keys.length, + required: 2 as const, + })), + }; +} + +/** Validate the entire proposed policy once, before any wallet creation or server registration. */ +export function buildRecoverablePolicyReview( + input: RecoverablePolicyDraftInput +): RecoverablePolicyReview { + if (input && typeof input === 'object') { + assertOnlyKeys( + input, + ['version', 'network', 'mobile', 'hardware', 'server', 'inheritance'], + 'Policy draft' + ); + } + if ( + input?.version !== RECOVERABLE_POLICY_DRAFT_VERSION || + input.network !== NetworkType.TESTNET + ) { + fail('TESTNET_ONLY', 'Recoverable Wallet policy drafts are testnet-only'); + } + const mobile = validateMobile(input.mobile); + const hardware = validateHardware(input.hardware); + const server = validateServer(input.server); + const inheritance = input.inheritance ? validateInheritance(input.inheritance) : null; + assertDistinctSigners([mobile, hardware, server, ...(inheritance ? [inheritance.signer] : [])]); + + // These NFC cards can sign, but cannot verify the complete delayed policy on-device. + if ( + inheritance && + [SignerType.TAPSIGNER, SignerType.SATOCHIP, SignerType.JADE].includes(hardware.signerType) + ) { + fail('UNSUPPORTED_HARDWARE_POLICY', 'This hardware cannot verify the Inheritance Key policy'); + } + + const candidateMiniscript = inheritance + ? compileInheritanceCandidate([mobile, hardware, server], inheritance) + : null; + + return { + kind: 'public-policy-review', + version: RECOVERABLE_POLICY_DRAFT_VERSION, + network: NetworkType.TESTNET, + base: { required: 2, total: 3, signers: [mobile, hardware, server] }, + inheritance: inheritance + ? { required: 2, total: 4, signer: inheritance.signer, activation: inheritance.activation } + : null, + baseVaultScheme: inheritance + ? null + : { m: 2, n: 3, multisigScriptType: MultisigScriptType.DEFAULT_MULTISIG }, + candidateMiniscript, + hardwarePolicyStatus: inheritance + ? 'inheritance-policy-not-device-tested' + : 'plain-multisig-not-device-tested', + fundable: false, + }; +} diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts index 063d9dc26..bdc95dfb2 100644 --- a/src/store/sagas/bhr.ts +++ b/src/store/sagas/bhr.ts @@ -10,6 +10,7 @@ import { } from 'src/utils/service-utilities/encryption'; import BIP85 from 'src/services/wallets/operations/BIP85'; import DeviceInfo from 'react-native-device-info'; +import NativeConfig from 'react-native-config'; import { KeeperApp } from 'src/models/interfaces/KeeperApp'; import { RealmSchema } from 'src/storage/realm/enum'; import Relay from 'src/services/backend/Relay'; @@ -93,6 +94,7 @@ import { addToUaiStackWorker, uaiActionedWorker } from './uai'; import { addAccount, saveDefaultWalletState, setRecoveryKeyBackedUp } from '../reducers/account'; import { loadConciergeTickets, loadConciergeUser } from '../reducers/concierge'; import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory'; +import { shouldRestoreFallbackMobileWallet } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; export function* updateAppImageWorker({ payload, @@ -401,7 +403,18 @@ function* getAppImageWorker({ payload }) { previousVersion ); - if ((!appImage.wallets || !Object.entries(appImage.wallets).length) && !allVaultImages.length) { + if ( + shouldRestoreFallbackMobileWallet( + { + emptyWalletFlag: NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING, + previewFlag: NativeConfig.KEEPER_PREVIEW, + testnetOnlyFlag: NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY, + bundleId: DeviceInfo.getBundleId(), + }, + Boolean(appImage.wallets && Object.entries(appImage.wallets).length), + Boolean(allVaultImages.length) + ) + ) { // recreate first wallet const defaultWallet: NewWalletInfo = { walletType: WalletType.DEFAULT, diff --git a/src/store/sagas/settings.ts b/src/store/sagas/settings.ts index 08d87d350..18810164e 100644 --- a/src/store/sagas/settings.ts +++ b/src/store/sagas/settings.ts @@ -22,8 +22,11 @@ import { SubscriptionTier } from 'src/models/enums/SubscriptionTier'; import { AppIconWrapper } from 'src/utils/AppIconWrapper'; import ThemeMode from 'src/models/enums/ThemeMode'; import { updateDefaultWalletCreatedByAppId } from '../reducers/account'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import { shouldAutomaticallyCreateMobileWallet } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; -function* changeBitcoinNetworkWorker({ payload }) { +export function* changeBitcoinNetworkWorker({ payload }) { let activeNode; const { network, callback } = payload; try { @@ -58,7 +61,15 @@ function* changeBitcoinNetworkWorker({ payload }) { // Create default wallet and signer if not created already const { defaultWalletCreatedByAppId } = yield select((state: RootState) => state.account); const defaultWalletCreated = defaultWalletCreatedByAppId[id]; - if (!defaultWalletCreated[bitcoinNetworkType]) { + if ( + shouldAutomaticallyCreateMobileWallet({ + emptyWalletFlag: NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING, + previewFlag: NativeConfig.KEEPER_PREVIEW, + testnetOnlyFlag: NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY, + bundleId: DeviceInfo.getBundleId(), + }) && + !defaultWalletCreated[bitcoinNetworkType] + ) { const cosigner = yield call(getCosignerDetails, primaryMnemonic, 0); const hw = setupKeeperSigner(cosigner); if (hw) { diff --git a/src/store/sagas/storage.ts b/src/store/sagas/storage.ts index 99eaa08f3..ffe1131d1 100644 --- a/src/store/sagas/storage.ts +++ b/src/store/sagas/storage.ts @@ -3,6 +3,7 @@ import { call, put, select, fork } from 'redux-saga/effects'; import { generateEncryptionKey } from 'src/utils/service-utilities/encryption'; import BIP85 from 'src/services/wallets/operations/BIP85'; import DeviceInfo from 'react-native-device-info'; +import NativeConfig from 'react-native-config'; import { KeeperApp } from 'src/models/interfaces/KeeperApp'; import { RealmSchema } from 'src/storage/realm/enum'; import { AppSubscriptionLevel, SubscriptionTier } from 'src/models/enums/SubscriptionTier'; @@ -41,6 +42,7 @@ import { } from '../reducers/account'; import { loadConciergeTickets, loadConciergeUser } from '../reducers/concierge'; import LoginMethod from 'src/models/enums/LoginMethod'; +import { shouldAutomaticallyCreateMobileWallet } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; export function* setupKeeperAppWorker({ payload }) { try { @@ -95,27 +97,36 @@ export function* setupKeeperAppWorker({ payload }) { yield put(addAccount(appID)); - const defaultWallet: NewWalletInfo = { - walletType: WalletType.DEFAULT, - walletDetails: { - name: 'Mobile Wallet', - description: '', - instanceNum: 0, - derivationPath: WalletUtilities.getDerivationPath( - false, - bitcoinNetworkType, - 0, - DerivationPurpose.BIP84 - ), - }, - }; - + const createDefaultWallet = shouldAutomaticallyCreateMobileWallet({ + emptyWalletFlag: NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING, + previewFlag: NativeConfig.KEEPER_PREVIEW, + testnetOnlyFlag: NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY, + bundleId: DeviceInfo.getBundleId(), + }); + let defaultWallet: NewWalletInfo; + if (createDefaultWallet) { + defaultWallet = { + walletType: WalletType.DEFAULT, + walletDetails: { + name: 'Mobile Wallet', + description: '', + instanceNum: 0, + derivationPath: WalletUtilities.getDerivationPath( + false, + bitcoinNetworkType, + 0, + DerivationPurpose.BIP84 + ), + }, + }; + } const recoveryKeySigner = setupRecoveryKeySigningKey(primaryMnemonic); - yield call(addNewWalletsWorker, { payload: [defaultWallet] }); + if (createDefaultWallet) yield call(addNewWalletsWorker, { payload: [defaultWallet] }); yield call(addSigningDeviceWorker, { payload: { signers: [recoveryKeySigner] } }); - yield put( - updateDefaultWalletCreatedByAppId({ appId: appID, networkType: bitcoinNetworkType }) - ); + if (createDefaultWallet) + yield put( + updateDefaultWalletCreatedByAppId({ appId: appID, networkType: bitcoinNetworkType }) + ); yield put(setAppId(appID)); yield put(setAppCreated(true)); yield put(resetRealyWalletState()); diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index a9fe41ea6..136c64d2d 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -1,6 +1,9 @@ import React from 'react'; import { Dimensions, PixelRatio, StyleSheet } from 'react-native'; +import { NativeBaseProvider } from '@gluestack-ui/themed-native-base'; import { fireEvent, render } from '@testing-library/react-native'; +import WalletCreationChooser from '../../src/components/WalletCreationChooser'; +import { customTheme } from '../../src/navigation/themes'; import RecoverableWalletPreviewApp from '../../src/preview/recoverable-wallet/RecoverableWalletPreviewApp'; jest.mock('src/components/ScreenWrapper', () => { @@ -23,6 +26,18 @@ jest.mock('src/components/KeeperText', () => { return ({ children, ...props }) => {children}; }); +function enterRecoveryOptions(screen) { + fireEvent.press(screen.getByTestId('primary-Add Wallet')); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + fireEvent.press(screen.getByTestId('primary-Continue')); + fireEvent.press(screen.getByTestId('preview-hardware-Coldcard')); + fireEvent.press(screen.getByTestId('primary-Continue')); + fireEvent.press(screen.getByTestId('preview-continue-simulation')); + fireEvent.press(screen.getByTestId('primary-Review Policy')); + fireEvent.press(screen.getByTestId('primary-Finish Preview')); + fireEvent.press(screen.getByTestId('primary-Recovery Options')); +} + describe('Recoverable Wallet preview on a small screen', () => { beforeEach(() => { jest @@ -33,10 +48,12 @@ describe('Recoverable Wallet preview on a small screen', () => { test('keeps security copy available, reaches one final review, and resumes after cancel', () => { const screen = render(); + expect(screen.getByTestId('preview-add-wallet')).toHaveTextContent('No wallets yet'); + fireEvent.press(screen.getByTestId('primary-Add Wallet')); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); expect(screen.getByTestId('preview-simulation-banner')).toHaveTextContent( 'Simulated walkthrough' ); - fireEvent.press(screen.getByTestId('primary-Start Preview')); expect(screen.getByTestId('preview-automatic')).toHaveTextContent( 'No key material has been generated' ); @@ -57,16 +74,143 @@ describe('Recoverable Wallet preview on a small screen', () => { fireEvent.press(screen.getByTestId('primary-Simulate Error')); expect(screen.getByTestId('preview-connection-error')).toHaveTextContent('Simulated error 2'); fireEvent.press(screen.getByTestId('preview-cancel')); - fireEvent.press(screen.getByTestId('primary-Resume')); + expect(screen.getByTestId('wallet-creation-chooser')).toHaveTextContent('will resume'); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); expect(screen.getByTestId('preview-connect')).toHaveTextContent('Coldcard'); fireEvent.press(screen.getByTestId('preview-continue-simulation')); fireEvent.press(screen.getByTestId('preview-inheritance-toggle')); fireEvent.press(screen.getByTestId('primary-Review Policy')); expect(screen.getByTestId('preview-review')).toHaveTextContent('Spending now · 2 of 3'); expect(screen.getByTestId('preview-review')).toHaveTextContent( - 'Inheritance Key and any eligible original signer' + 'designated second signer available without Server Key' ); + expect(screen.getByTestId('preview-review')).toHaveTextContent('fixed on-chain unlock date'); fireEvent.press(screen.getByTestId('primary-Finish Preview')); expect(screen.getByTestId('preview-complete')).toHaveTextContent('No wallet was created'); + fireEvent.press(screen.getByTestId('preview-done')); + expect(screen.getByTestId('wallet-creation-chooser')).toBeTruthy(); + }); + + test('navigates the three-choice entry and keeps other paths simulated', () => { + const screen = render(); + fireEvent.press(screen.getByTestId('primary-Add Wallet')); + const chooser = screen.getByTestId('wallet-creation-chooser'); + expect(chooser).toHaveTextContent('Simple Wallet'); + expect(chooser).toHaveTextContent('Seedless Wallet'); + expect(chooser).toHaveTextContent('Advanced Wallet'); + expect(chooser).toHaveTextContent('Your Keeper Recovery Key still matters'); + const seedlessTitle = screen.getByText('Seedless Wallet'); + expect(seedlessTitle.props.allowFontScaling).toBe(true); + expect(seedlessTitle.props.numberOfLines).toBeUndefined(); + expect(StyleSheet.flatten(seedlessTitle.props.style).lineHeight).toBeGreaterThan(25); + + fireEvent.press(screen.getByTestId('wallet-choice-simple')); + expect(screen.getByTestId('preview-simple-wallet')).toHaveTextContent('Hot Wallet'); + expect(screen.getByTestId('preview-simple-wallet')).toHaveTextContent('Cold Wallet'); + fireEvent.press(screen.getByTestId('preview-choice-hot')); + expect(screen.getByTestId('preview-hot-wallet')).toHaveTextContent('No key is generated'); + fireEvent.press(screen.getByTestId('preview-back')); + fireEvent.press(screen.getByTestId('preview-choice-cold')); + expect(screen.getByTestId('preview-cold-wallet')).toHaveTextContent('No device is connected'); + fireEvent.press(screen.getByTestId('preview-choose-another-wallet')); + + fireEvent.press(screen.getByTestId('wallet-choice-advanced')); + expect(screen.getByTestId('preview-advanced-wallet')).toHaveTextContent( + 'Advanced Wallet creation is not connected' + ); + fireEvent.press(screen.getByTestId('preview-back')); + fireEvent.press(screen.getByTestId('wallet-choice-import')); + expect(screen.getByTestId('preview-import-unavailable')).toHaveTextContent( + 'No existing wallet or key was accessed' + ); + fireEvent.press(screen.getByTestId('preview-back')); + fireEvent.press(screen.getByTestId('preview-back')); + expect(screen.getByTestId('preview-add-wallet')).toHaveTextContent('No wallets yet'); + }); + + test('the shared chooser hides Seedless Wallet unless the caller explicitly enables it', () => { + const onSeedlessWallet = jest.fn(); + const screen = render( + + + + ); + expect(screen.queryByTestId('wallet-choice-seedless')).toBeNull(); + expect(onSeedlessWallet).not.toHaveBeenCalled(); + }); + + test('shows separate cloud and contact options without claiming backup readback', () => { + const screen = render(); + enterRecoveryOptions(screen); + expect(screen.getByTestId('preview-recovery-options')).toHaveTextContent( + 'No Mobile Key, encrypted cloud blob, contact credential, or server exchange exists' + ); + fireEvent.press(screen.getByTestId('preview-recovery-cloud')); + expect(screen.getByTestId('preview-cloud-backup')).toHaveTextContent('readback not verified'); + const readbackCopy = screen.getByText(/No encrypted Mobile Key was written or downloaded/); + expect(readbackCopy.props.allowFontScaling).toBe(true); + expect(StyleSheet.flatten(readbackCopy.props.style).lineHeight).toBeGreaterThan(23); + fireEvent.press(screen.getByTestId('primary-Simulate Offline')); + expect(screen.getByTestId('preview-cloud-offline')).toHaveTextContent( + 'No upload was attempted' + ); + fireEvent.press(screen.getByTestId('preview-recovery-back')); + fireEvent.press(screen.getByTestId('preview-recovery-contact')); + expect(screen.getByTestId('preview-contact-offline')).toHaveTextContent( + 'Contact recovery cannot proceed' + ); + fireEvent.press(screen.getByTestId('preview-back')); + fireEvent.press(screen.getByTestId('preview-recovery-cloud')); + fireEvent.press(screen.getByTestId('primary-Try Again')); + expect(screen.getByTestId('preview-cloud-unverified')).toHaveTextContent( + 'READBACK NOT VERIFIED' + ); + fireEvent.press(screen.getByTestId('preview-recovery-back')); + fireEvent.press(screen.getByTestId('preview-recovery-contact')); + expect(screen.getByTestId('preview-contact-blocked')).toHaveTextContent( + 'No invitation can be sent' + ); + }); + + test('samples invite and request decisions without an enrollment or restored key', () => { + const screen = render(); + enterRecoveryOptions(screen); + fireEvent.press(screen.getByTestId('preview-recovery-contact')); + fireEvent.press(screen.getByTestId('primary-Sample Invite')); + expect(screen.getByTestId('preview-sample-invitation')).toHaveTextContent('not sent'); + fireEvent.press(screen.getByTestId('preview-invite-decline')); + expect(screen.getByTestId('preview-invite-result')).toHaveTextContent('No credential'); + fireEvent.press(screen.getByTestId('preview-invite-reset')); + fireEvent.press(screen.getByTestId('preview-invite-expire')); + expect(screen.getByTestId('preview-invite-result')).toHaveTextContent('SIMULATED EXPIRY'); + fireEvent.press(screen.getByTestId('preview-invite-reset')); + fireEvent.press(screen.getByTestId('primary-Simulate Approval')); + expect(screen.getByTestId('preview-invite-result')).toHaveTextContent( + 'No credential was enrolled' + ); + + fireEvent.press(screen.getByTestId('preview-sample-request')); + expect(screen.getByTestId('preview-sample-contact-request')).toHaveTextContent('not sent'); + fireEvent.press(screen.getByTestId('preview-request-decline')); + expect(screen.getByTestId('preview-request-result')).toHaveTextContent( + 'No Mobile Key was restored' + ); + fireEvent.press(screen.getByTestId('preview-request-reset')); + fireEvent.press(screen.getByTestId('preview-request-expire')); + expect(screen.getByTestId('preview-request-result')).toHaveTextContent('SIMULATED EXPIRY'); + fireEvent.press(screen.getByTestId('preview-request-reset')); + fireEvent.press(screen.getByTestId('primary-Simulate Approval')); + expect(screen.getByTestId('preview-request-result')).toHaveTextContent( + 'No response was encrypted or delivered, and no Mobile Key was restored' + ); + fireEvent.press(screen.getByTestId('preview-back')); + expect(screen.getByTestId('preview-recovery-options')).toBeTruthy(); + fireEvent.press(screen.getByTestId('preview-back')); + expect(screen.getByTestId('preview-complete')).toBeTruthy(); }); }); diff --git a/tests/preview/walletChoiceScreen.test.tsx b/tests/preview/walletChoiceScreen.test.tsx new file mode 100644 index 000000000..dcd7f4a92 --- /dev/null +++ b/tests/preview/walletChoiceScreen.test.tsx @@ -0,0 +1,113 @@ +import React from 'react'; +import { fireEvent, render } from '@testing-library/react-native'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import { useAppSelector } from '../../src/store/hooks'; +import { NetworkType } from '../../src/services/wallets/enums'; +import WalletChoiceScreen from '../../src/screens/AddWalletScreen/WalletChoiceScreen'; + +const mockNavigation = { navigate: jest.fn(), goBack: jest.fn() }; + +jest.mock('@react-navigation/native', () => ({ + useNavigation: () => mockNavigation, +})); + +jest.mock('react-native-config', () => ({ + __esModule: true, + default: { + KEEPER_EMPTY_WALLET_ONBOARDING: 'true', + KEEPER_PREVIEW: 'true', + KEEPER_PREVIEW_TESTNET_ONLY: 'true', + }, +})); + +jest.mock('react-native-device-info', () => ({ + __esModule: true, + default: { getBundleId: jest.fn() }, +})); + +jest.mock('src/store/hooks', () => ({ useAppSelector: jest.fn() })); +jest.mock('@gluestack-ui/themed-native-base', () => ({ + useColorMode: () => ({ colorMode: 'light' }), +})); +jest.mock('src/components/ScreenWrapper', () => { + const React = require('react'); + const { View } = require('react-native'); + return ({ children }) => {children}; +}); +jest.mock('src/components/WalletHeader', () => { + const React = require('react'); + const { Pressable, Text } = require('react-native'); + return ({ title, onPressHandler }) => ( + + {title} + + ); +}); +jest.mock('src/components/KeeperText', () => { + const React = require('react'); + const { Text } = require('react-native'); + return ({ children, ...props }) => {children}; +}); + +describe('guarded Wallets chooser route', () => { + beforeEach(() => { + mockNavigation.navigate.mockClear(); + mockNavigation.goBack.mockClear(); + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + (useAppSelector as jest.Mock).mockReturnValue(NetworkType.TESTNET); + NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING = 'true'; + }); + + test('fails closed for a normal Keeper app identity and missing flag', () => { + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue('io.hexawallet.keeper'); + const normal = render(); + expect(normal.queryByTestId('wallet-creation-chooser')).toBeNull(); + expect(mockNavigation.goBack).toHaveBeenCalledTimes(1); + normal.unmount(); + + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + (NativeConfig as any).KEEPER_EMPTY_WALLET_ONBOARDING = undefined; + const unflagged = render(); + expect(unflagged.queryByTestId('wallet-creation-chooser')).toBeNull(); + expect(mockNavigation.goBack).toHaveBeenCalledTimes(2); + }); + + test('fails closed if the active network is not testnet', () => { + (useAppSelector as jest.Mock).mockReturnValue(NetworkType.MAINNET); + const screen = render(); + expect(screen.queryByTestId('wallet-creation-chooser')).toBeNull(); + expect(mockNavigation.goBack).toHaveBeenCalledTimes(1); + }); + + test('offers guarded choices without opening an unverified Seedless or Simple flow', () => { + const screen = render(); + expect(screen.getByTestId('wallet-creation-chooser')).toHaveTextContent('Seedless Wallet'); + fireEvent.press(screen.getByTestId('wallet-choice-simple')); + fireEvent.press(screen.getByTestId('wallet-choice-hot')); + expect(screen.getByTestId('wallet-choice-hot-unavailable')).toHaveTextContent( + 'No wallet or key has been created' + ); + fireEvent.press(screen.getByTestId('wallet-choice-back')); + fireEvent.press(screen.getByTestId('wallet-choice-cold')); + expect(screen.getByTestId('wallet-choice-cold-unavailable')).toHaveTextContent( + 'verified setup flow' + ); + fireEvent.press(screen.getByTestId('wallet-choice-back')); + fireEvent.press(screen.getByTestId('wallet-choice-back')); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(screen.getByTestId('wallet-choice-seedless-unavailable')).toHaveTextContent( + 'No Mobile Key, Server Key, hardware connection, or wallet is created' + ); + expect(mockNavigation.navigate).not.toHaveBeenCalled(); + fireEvent.press(screen.getByTestId('wallet-choice-back')); + fireEvent.press(screen.getByTestId('wallet-choice-advanced')); + expect(mockNavigation.navigate).toHaveBeenCalledWith('AddNewWallet'); + fireEvent.press(screen.getByTestId('wallet-choice-import')); + expect(mockNavigation.navigate).toHaveBeenCalledWith('VaultConfigurationCreation'); + }); +}); diff --git a/tests/services/emptyWalletNetworkSaga.test.ts b/tests/services/emptyWalletNetworkSaga.test.ts new file mode 100644 index 000000000..aed54b8e0 --- /dev/null +++ b/tests/services/emptyWalletNetworkSaga.test.ts @@ -0,0 +1,83 @@ +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import { NetworkType } from 'src/services/wallets/enums'; +import { changeBitcoinNetworkWorker } from 'src/store/sagas/settings'; +import { getCosignerDetails } from 'src/services/wallets/factories/WalletFactory'; + +jest.mock('react-native-config', () => ({ + KEEPER_EMPTY_WALLET_ONBOARDING: 'true', + KEEPER_PREVIEW: 'true', + KEEPER_PREVIEW_TESTNET_ONLY: 'true', +})); + +jest.mock('react-native-device-info', () => ({ + getBundleId: jest.fn(() => 'io.hexawallet.keeper.recoverablepreview'), +})); + +jest.mock('src/services/electrum/node', () => ({ + __esModule: true, + default: { getAllNodes: jest.fn(() => []) }, +})); + +jest.mock('src/services/electrum/client', () => ({ + __esModule: true, + default: { setActivePeer: jest.fn(), connect: jest.fn() }, +})); + +jest.mock('src/storage/realm/dbManager', () => ({ + __esModule: true, + default: { createObjectBulk: jest.fn(), getObjectByIndex: jest.fn() }, +})); + +jest.mock('src/services/wallets/operations/utils', () => ({ + __esModule: true, + default: { getDerivationPath: jest.fn(() => "m/84'/1'/0'") }, +})); + +jest.mock('src/services/wallets/factories/WalletFactory', () => ({ + getCosignerDetails: jest.fn(), +})); + +jest.mock('src/hardware/signerSetup', () => ({ setupKeeperSigner: jest.fn() })); +jest.mock('src/store/sagas/wallets', () => ({ addNewWalletsWorker: function* () {} })); +jest.mock('src/utils/AppIconWrapper', () => ({ AppIconWrapper: jest.fn() })); + +const reachWalletDecision = (defaultWalletCreatedByAppId) => { + const callback = jest.fn(); + const generator: Generator = changeBitcoinNetworkWorker({ + payload: { network: NetworkType.TESTNET, callback }, + }); + generator.next(); // set network + generator.next(); // fetch fees + generator.next(); // select active network + generator.next({ bitcoinNetworkType: NetworkType.TESTNET }); // add node + generator.next(); // connect Electrum + generator.next(); // load KeeperApp + generator.next({ id: 'app-id', primaryMnemonic: 'recovery-key' }); // select wallet state + return { generator, callback, effect: generator.next({ defaultWalletCreatedByAppId }) }; +}; + +describe('network switch default wallet gate', () => { + afterEach(() => { + (NativeConfig as any).KEEPER_EMPTY_WALLET_ONBOARDING = 'true'; + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + }); + + it('does not create a Mobile Wallet when switching an intentionally empty preview', () => { + const { callback, effect } = reachWalletDecision({}); + expect(effect.done).toBe(true); + expect(callback).toHaveBeenCalledWith(true); + }); + + it('preserves the normal switch behavior when the gate is absent', () => { + (NativeConfig as any).KEEPER_EMPTY_WALLET_ONBOARDING = undefined; + const { effect } = reachWalletDecision({ + 'app-id': { [NetworkType.TESTNET]: false, [NetworkType.MAINNET]: false }, + }); + expect(effect.done).toBe(false); + expect((effect.value as any).type).toBe('CALL'); + expect((effect.value as any).payload.fn).toBe(getCosignerDetails); + }); +}); diff --git a/tests/services/emptyWalletOnboarding.test.ts b/tests/services/emptyWalletOnboarding.test.ts new file mode 100644 index 000000000..2a8467e02 --- /dev/null +++ b/tests/services/emptyWalletOnboarding.test.ts @@ -0,0 +1,63 @@ +import { + isEmptyWalletOnboardingEnabled, + shouldAutomaticallyCreateMobileWallet, + shouldRestoreFallbackMobileWallet, +} from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; + +const previewGate = { + emptyWalletFlag: 'true', + previewFlag: 'true', + testnetOnlyFlag: 'true', + bundleId: 'io.hexawallet.keeper.recoverablepreview', +}; + +describe('empty Wallet onboarding gate', () => { + it('preserves automatic Mobile Wallet creation by default', () => { + expect( + shouldAutomaticallyCreateMobileWallet({ ...previewGate, emptyWalletFlag: undefined }) + ).toBe(true); + expect( + shouldAutomaticallyCreateMobileWallet({ ...previewGate, emptyWalletFlag: 'false' }) + ).toBe(true); + }); + + it('is active only for the exact testnet preview identity and flags', () => { + expect(isEmptyWalletOnboardingEnabled(previewGate)).toBe(true); + expect( + isEmptyWalletOnboardingEnabled({ + ...previewGate, + bundleId: 'io.hexawallet.hexakeeper.recoverablepreview', + }) + ).toBe(true); + expect(shouldAutomaticallyCreateMobileWallet(previewGate)).toBe(false); + expect( + shouldAutomaticallyCreateMobileWallet({ + ...previewGate, + bundleId: 'io.hexawallet.keeper', + }) + ).toBe(true); + expect( + shouldAutomaticallyCreateMobileWallet({ ...previewGate, testnetOnlyFlag: undefined }) + ).toBe(true); + expect(shouldAutomaticallyCreateMobileWallet({ ...previewGate, previewFlag: undefined })).toBe( + true + ); + }); + + it('keeps an intentionally empty restored preview empty while preserving legacy fallback', () => { + expect(shouldRestoreFallbackMobileWallet(previewGate, false, false)).toBe(false); + expect( + shouldRestoreFallbackMobileWallet( + { ...previewGate, emptyWalletFlag: undefined }, + false, + false + ) + ).toBe(true); + expect( + shouldRestoreFallbackMobileWallet({ ...previewGate, emptyWalletFlag: undefined }, true, false) + ).toBe(false); + expect( + shouldRestoreFallbackMobileWallet({ ...previewGate, emptyWalletFlag: undefined }, false, true) + ).toBe(false); + }); +}); diff --git a/tests/services/emptyWalletSetupSaga.test.ts b/tests/services/emptyWalletSetupSaga.test.ts new file mode 100644 index 000000000..48f27188e --- /dev/null +++ b/tests/services/emptyWalletSetupSaga.test.ts @@ -0,0 +1,89 @@ +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import { NetworkType } from 'src/services/wallets/enums'; +import { setupKeeperAppWorker } from 'src/store/sagas/storage'; +import { addNewWalletsWorker, addSigningDeviceWorker } from 'src/store/sagas/wallets'; + +jest.mock('react-native-config', () => ({ + KEEPER_EMPTY_WALLET_ONBOARDING: 'true', + KEEPER_PREVIEW: 'true', + KEEPER_PREVIEW_TESTNET_ONLY: 'true', +})); + +jest.mock('react-native-device-info', () => ({ + getBundleId: jest.fn(() => 'io.hexawallet.keeper.recoverablepreview'), + getVersion: jest.fn(() => '2.5.13'), + getBuildNumber: jest.fn(() => '1'), +})); + +jest.mock('src/hardware/signerSetup', () => ({ + setupRecoveryKeySigningKey: jest.fn(() => ({ id: 'recovery-key-signer' })), +})); + +jest.mock('src/services/wallets/operations/utils', () => ({ + __esModule: true, + default: { getDerivationPath: jest.fn(() => "m/84'/1'/0'") }, +})); + +jest.mock('src/store/sagas/wallets', () => ({ + addNewWalletsWorker: function* addNewWalletsWorker() {}, + addSigningDeviceWorker: function* addSigningDeviceWorker() {}, +})); + +jest.mock('src/services/backend/Relay', () => ({ + __esModule: true, + default: { createNewApp: jest.fn() }, +})); + +jest.mock('src/services/backend/SigningServer', () => ({ + __esModule: true, + default: {}, +})); + +jest.mock('src/storage/realm/dbManager', () => ({ + __esModule: true, + default: { getObjectByIndex: jest.fn(), createObject: jest.fn() }, +})); + +const recoveryKey = + 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; + +const nextAfterAppStored = () => { + const generator: Generator = setupKeeperAppWorker({ + payload: { appName: 'Preview', fcmToken: '' }, + }); + generator.next(); // select network + generator.next({ bitcoinNetworkType: NetworkType.TESTNET }); // load existing app + generator.next({ + id: 'app-id', + publicId: 'public-id', + primaryMnemonic: recoveryKey, + primarySeed: Buffer.alloc(64, 1), + imageEncryptionKey: 'encryption-key', + }); // create app with Relay + generator.next({ created: true }); // store KeeperApp + generator.next(); // add account + return generator.next().value; +}; + +describe('Keeper app setup default wallet gate', () => { + afterEach(() => { + (NativeConfig as any).KEEPER_EMPTY_WALLET_ONBOARDING = 'true'; + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + }); + + it('omits automatic wallet creation in the isolated preview', () => { + const effect = nextAfterAppStored() as any; + expect(effect.type).toBe('CALL'); + expect(effect.payload.fn).toBe(addSigningDeviceWorker); + }); + + it('retains the normal Keeper wallet creation effect when the gate is absent', () => { + (NativeConfig as any).KEEPER_EMPTY_WALLET_ONBOARDING = undefined; + const effect = nextAfterAppStored() as any; + expect(effect.type).toBe('CALL'); + expect(effect.payload.fn).toBe(addNewWalletsWorker); + }); +}); diff --git a/tests/services/recoverable/contactRecoveryFlow.test.ts b/tests/services/recoverable/contactRecoveryFlow.test.ts new file mode 100644 index 000000000..3b655cc06 --- /dev/null +++ b/tests/services/recoverable/contactRecoveryFlow.test.ts @@ -0,0 +1,256 @@ +import { NetworkType } from 'src/services/wallets/enums'; +import { + ContactApprovalEnvelopeMetadata, + ContactRecoveryFlowError, + EncryptedCloudReadbackReceipt, + RECOVERABLE_PREVIEW_CLOUD_NAMESPACE, + decideContactRequest, + initialContactEnrollment, + initialContactRecovery, + reduceContactEnrollment, + reduceContactRecovery, + reviewContactRequest, +} from 'src/services/wallets/recoverable/contactRecoveryFlow'; + +const NOW = 1_700_000_000; +const WALLET = 'ab'.repeat(32).toUpperCase(); +const DIGEST = 'a'.repeat(64); + +function readback(): EncryptedCloudReadbackReceipt { + return { + kind: 'encrypted-mobile-key-readback-v1', + network: NetworkType.TESTNET, + namespace: RECOVERABLE_PREVIEW_CLOUD_NAMESPACE, + walletPolicyHash: WALLET, + objectId: 'test-object-1', + writtenCiphertextSha256: DIGEST, + readCiphertextSha256: DIGEST, + checkedAt: NOW, + }; +} + +function request() { + return { + requestId: 'test-request-1', + walletPolicyHash: WALLET, + contactCredentialId: 'contact-key-1', + replacementDeviceKeyId: 'new-device-key-1', + expiresAt: NOW + 600, + }; +} + +function expectCode(action: () => unknown, code: string) { + try { + action(); + throw new Error(`Expected ${code}`); + } catch (error) { + expect(error).toBeInstanceOf(ContactRecoveryFlowError); + expect((error as ContactRecoveryFlowError).code).toBe(code); + } +} + +describe('Recovery Contact client-only flow', () => { + test('enrollment needs cloud readback, handles offline, and stops before crypto enrollment', () => { + let state = reduceContactEnrollment(initialContactEnrollment, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: WALLET, + }); + state = reduceContactEnrollment(state, { type: 'CLOUD_OFFLINE' }); + expect(state.stage).toBe('cloud-offline'); + expectCode( + () => + reduceContactEnrollment(state, { + type: 'INVITE', + invitationId: 'invite-1', + expiresAt: NOW + 60, + now: NOW, + }), + 'INVALID_TRANSITION' + ); + state = reduceContactEnrollment(state, { type: 'RETRY_CLOUD' }); + state = reduceContactEnrollment(state, { type: 'CLOUD_READBACK', receipt: readback() }); + state = reduceContactEnrollment(state, { + type: 'INVITE', + invitationId: 'invite-1', + expiresAt: NOW + 60, + now: NOW, + }); + state = reduceContactEnrollment(state, { + type: 'CONTACT_ACCEPTED', + invitationId: 'invite-1', + contactCredentialId: 'contact-key-1', + now: NOW + 1, + }); + expect(state.stage).toBe('awaiting-cryptographic-enrollment'); + expect(state.contactCredentialId).toBe('contact-key-1'); + expect(JSON.stringify(state)).not.toMatch(/xpriv|mnemonic|recoveryCode/i); + }); + + test('a write receipt without matching preview readback cannot start enrollment', () => { + const started = reduceContactEnrollment(initialContactEnrollment, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: WALLET, + }); + const wrongBytes = readback(); + wrongBytes.readCiphertextSha256 = 'b'.repeat(64); + expectCode( + () => reduceContactEnrollment(started, { type: 'CLOUD_READBACK', receipt: wrongBytes }), + 'READBACK_MISMATCH' + ); + const wrongNamespace = readback(); + wrongNamespace.namespace = 'production' as any; + expectCode( + () => reduceContactEnrollment(started, { type: 'CLOUD_READBACK', receipt: wrongNamespace }), + 'INVALID_READBACK' + ); + const wrongPolicy = readback(); + wrongPolicy.walletPolicyHash = 'cd'.repeat(32); + expectCode( + () => reduceContactEnrollment(started, { type: 'CLOUD_READBACK', receipt: wrongPolicy }), + 'INVALID_READBACK' + ); + const shortFingerprint = readback(); + shortFingerprint.walletPolicyHash = 'ABCDEF12'; + expectCode( + () => reduceContactEnrollment(started, { type: 'CLOUD_READBACK', receipt: shortFingerprint }), + 'INVALID_POLICY_HASH' + ); + }); + + test('contact can explicitly decline, and an invitation cannot be accepted after expiry', () => { + let state = reduceContactEnrollment(initialContactEnrollment, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: WALLET, + }); + state = reduceContactEnrollment(state, { type: 'CLOUD_READBACK', receipt: readback() }); + state = reduceContactEnrollment(state, { + type: 'INVITE', + invitationId: 'invite-1', + expiresAt: NOW + 5, + now: NOW, + }); + expectCode( + () => + reduceContactEnrollment(state, { + type: 'CONTACT_ACCEPTED', + invitationId: 'invite-1', + contactCredentialId: 'contact-key-1', + now: NOW + 5, + }), + 'REQUEST_EXPIRED' + ); + expect(reduceContactEnrollment(state, { type: 'EXPIRE', now: NOW + 5 }).stage).toBe('expired'); + expect( + reduceContactEnrollment(state, { + type: 'CONTACT_DECLINED', + invitationId: 'invite-1', + now: NOW + 1, + }).stage + ).toBe('declined'); + }); + + test('the stronger option requires a separate code check before contacting anyone', () => { + let state = reduceContactRecovery(initialContactRecovery, { + type: 'START', + assurance: 'cloud-contact-and-code', + walletPolicyHash: WALLET, + contactCredentialId: 'contact-key-1', + }); + state = reduceContactRecovery(state, { type: 'CLOUD_READBACK', receipt: readback() }); + expect(state.stage).toBe('awaiting-code-verification'); + expectCode( + () => reduceContactRecovery(state, { type: 'REQUEST_CONTACT', request: request(), now: NOW }), + 'INVALID_TRANSITION' + ); + state = reduceContactRecovery(state, { type: 'CODE_VERIFIED' }); + state = reduceContactRecovery(state, { type: 'REQUEST_CONTACT', request: request(), now: NOW }); + expect(state.codeVerified).toBe(true); + expect(state.stage).toBe('waiting-for-contact'); + expect(JSON.stringify(state)).not.toContain('recoveryCode'); + }); + + test('cloud and contact option can use an independent request after readback', () => { + let state = reduceContactRecovery(initialContactRecovery, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: WALLET, + contactCredentialId: 'contact-key-1', + }); + state = reduceContactRecovery(state, { type: 'CLOUD_OFFLINE' }); + expect(state.stage).toBe('cloud-offline'); + state = reduceContactRecovery(state, { type: 'RETRY_CLOUD' }); + state = reduceContactRecovery(state, { type: 'CLOUD_READBACK', receipt: readback() }); + expect(state.stage).toBe('awaiting-contact-request'); + state = reduceContactRecovery(state, { type: 'REQUEST_CONTACT', request: request(), now: NOW }); + expect(state.stage).toBe('waiting-for-contact'); + }); + + test('approval metadata must bind to the active request and replacement device', () => { + let state = reduceContactRecovery(initialContactRecovery, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: WALLET, + contactCredentialId: 'contact-key-1', + }); + state = reduceContactRecovery(state, { type: 'CLOUD_READBACK', receipt: readback() }); + state = reduceContactRecovery(state, { type: 'REQUEST_CONTACT', request: request(), now: NOW }); + const envelope: ContactApprovalEnvelopeMetadata = { + ...request(), + kind: 'contact-approval-envelope-v1', + ciphertextSha256: 'b'.repeat(64), + }; + expectCode( + () => + reduceContactRecovery(state, { + type: 'APPROVAL_RECEIVED', + envelope: { ...envelope, requestId: 'old-request' }, + now: NOW + 1, + }), + 'REQUEST_MISMATCH' + ); + expectCode( + () => + reduceContactRecovery(state, { + type: 'APPROVAL_RECEIVED', + envelope: { ...envelope, replacementDeviceKeyId: 'attacker-device' }, + now: NOW + 1, + }), + 'ENVELOPE_MISMATCH' + ); + state = reduceContactRecovery(state, { type: 'APPROVAL_RECEIVED', envelope, now: NOW + 1 }); + expect(state.stage).toBe('awaiting-cryptographic-verification'); + expectCode( + () => reduceContactRecovery(state, { type: 'APPROVAL_RECEIVED', envelope, now: NOW + 2 }), + 'INVALID_TRANSITION' + ); + }); + + test('recovery decline and timeout are terminal without a restored-key state', () => { + let state = reduceContactRecovery(initialContactRecovery, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: WALLET, + contactCredentialId: 'contact-key-1', + }); + state = reduceContactRecovery(state, { type: 'CLOUD_READBACK', receipt: readback() }); + state = reduceContactRecovery(state, { type: 'REQUEST_CONTACT', request: request(), now: NOW }); + expect( + reduceContactRecovery(state, { + type: 'CONTACT_DECLINED', + requestId: 'test-request-1', + now: NOW + 1, + }).stage + ).toBe('declined'); + expect(reduceContactRecovery(state, { type: 'EXPIRE', now: NOW + 600 }).stage).toBe('expired'); + }); + + test('contact-side approval is intent only; expiry blocks it', () => { + const pending = reviewContactRequest(request(), NOW); + expect(decideContactRequest(pending, 'approve', NOW + 1).stage).toBe('approval-intent'); + expect(decideContactRequest(pending, 'decline', NOW + 1).stage).toBe('declined'); + expect(decideContactRequest(pending, 'approve', NOW + 600).stage).toBe('expired'); + }); +}); diff --git a/tests/services/recoverable/policyDraft.test.ts b/tests/services/recoverable/policyDraft.test.ts new file mode 100644 index 000000000..d13dba1f8 --- /dev/null +++ b/tests/services/recoverable/policyDraft.test.ts @@ -0,0 +1,221 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; +import { NetworkType, SignerType, MultisigScriptType } from 'src/services/wallets/enums'; +import { + buildRecoverablePolicyReview, + RecoverableHardwareSigner, + RecoverableInheritanceChoice, + RecoverableMobileSigner, + RecoverablePolicyDraftInput, + RecoverablePolicyDraftError, + RecoverableServerSigner, +} from 'src/services/wallets/recoverable/policyDraft'; +import { generateScriptWitnesses } from 'src/services/wallets/operations/miniscript/miniscript'; + +const bip32 = BIP32Factory(ecc); +const signerPath = "m/48'/1'/0'/2'"; + +function publicKeyFor(seedByte: number) { + const root = bip32.fromSeed(Buffer.alloc(32, seedByte), bitcoin.networks.testnet); + return { + masterFingerprint: root.fingerprint.toString('hex').toUpperCase(), + xpub: root.derivePath(signerPath).neutered().toBase58(), + derivationPath: signerPath, + }; +} + +function input(): RecoverablePolicyDraftInput { + const mobile: RecoverableMobileSigner = { + role: 'mobile', + signerType: SignerType.MOBILE_KEY, + ...publicKeyFor(1), + origin: { + kind: 'keeper-recovery-key-bip85', + version: 1, + ordinal: 0, + bip85Index: 1_000_000, + bip85Path: "m/83696968'/39'/0'/12'/1000000'", + }, + }; + const hardware: RecoverableHardwareSigner = { + role: 'hardware', + signerType: SignerType.COLDCARD, + ...publicKeyFor(2), + origin: { + kind: 'hardware-device', + device: SignerType.COLDCARD, + transport: 'qr', + sourceId: 'test-coldcard-1', + }, + }; + const server: RecoverableServerSigner = { + role: 'server', + signerType: SignerType.POLICY_SERVER, + ...publicKeyFor(3), + origin: { kind: 'keeper-server-key', sourceId: 'test-public-server-1' }, + }; + return { version: 1, network: NetworkType.TESTNET, mobile, hardware, server }; +} + +function inheritance(): RecoverableInheritanceChoice { + return { + signer: { + role: 'inheritance', + signerType: SignerType.SEED_WORDS, + ...publicKeyFor(4), + origin: { kind: 'externally-held-inheritance-key', sourceId: 'test-heir-1' }, + }, + activation: { + kind: 'block-height', + value: 85_012, + observedHeight: 85_000, + observedMedianTimePast: 1_700_000_000, + }, + }; +} + +function expectCode(action: () => unknown, code: string) { + try { + action(); + throw new Error(`Expected ${code}`); + } catch (error) { + expect(error).toBeInstanceOf(RecoverablePolicyDraftError); + expect((error as RecoverablePolicyDraftError).code).toBe(code); + } +} + +describe('public Recoverable Wallet policy draft', () => { + test('keeps a complete fixed 2-of-3 public review separate from wallet creation', () => { + const review = buildRecoverablePolicyReview(input()); + expect(review).toMatchObject({ + kind: 'public-policy-review', + network: NetworkType.TESTNET, + base: { required: 2, total: 3 }, + inheritance: null, + fundable: false, + hardwarePolicyStatus: 'plain-multisig-not-device-tested', + }); + expect(review.base.signers.map((signer) => signer.role)).toEqual([ + 'mobile', + 'hardware', + 'server', + ]); + expect(review.baseVaultScheme).toEqual({ + m: 2, + n: 3, + multisigScriptType: MultisigScriptType.DEFAULT_MULTISIG, + }); + expect(review.candidateMiniscript).toBeNull(); + expect(JSON.stringify(review)).not.toMatch(/xpriv|mnemonic|recoveryKey/i); + }); + + test('compiles an optional delayed 2-of-4 candidate before final policy review', () => { + const review = buildRecoverablePolicyReview({ ...input(), inheritance: inheritance() }); + const scheme = review.candidateMiniscript; + expect(review.inheritance).toMatchObject({ required: 2, total: 4 }); + expect(review.hardwarePolicyStatus).toBe('inheritance-policy-not-device-tested'); + expect(review.fundable).toBe(false); + expect(review.baseVaultScheme).toBeNull(); + expect(scheme?.policy).toContain('after(85012)'); + expect(scheme?.phases).toHaveLength(2); + expect(scheme?.phases[0]).toEqual({ timelock: 0, signerCount: 3, required: 2 }); + expect(scheme?.phases[1]).toEqual({ timelock: 85_012, signerCount: 4, required: 2 }); + expect(scheme?.miniscript).toBeTruthy(); + const { scriptWitnesses } = generateScriptWitnesses(scheme!.policy); + for (const originalSigner of ['K1', 'K2', 'K3']) { + expect( + scriptWitnesses.some( + (witness) => + witness.nLockTime === 85_012 && + witness.asm.includes('IK1') && + witness.asm.includes(originalSigner) + ) + ).toBe(true); + } + }); + + test('rejects a production network and mainnet xpub', () => { + const draft = input(); + expectCode( + () => buildRecoverablePolicyReview({ ...draft, network: NetworkType.MAINNET } as any), + 'TESTNET_ONLY' + ); + const mainnetRoot = bip32.fromSeed(Buffer.alloc(32, 5), bitcoin.networks.bitcoin); + draft.hardware.xpub = mainnetRoot.derivePath("m/48'/0'/0'/2'").neutered().toBase58(); + expectCode(() => buildRecoverablePolicyReview(draft), 'INVALID_XPUB'); + }); + + test('rejects a root tpub or a tpub from the wrong final derivation child', () => { + const root = bip32.fromSeed(Buffer.alloc(32, 7), bitcoin.networks.testnet); + const rootKey = input(); + rootKey.hardware.xpub = root.neutered().toBase58(); + expectCode(() => buildRecoverablePolicyReview(rootKey), 'INVALID_XPUB_ORIGIN'); + + const wrongChild = input(); + wrongChild.hardware.xpub = root.derivePath("m/48'/1'/0'/3'").neutered().toBase58(); + expectCode(() => buildRecoverablePolicyReview(wrongChild), 'INVALID_XPUB_ORIGIN'); + }); + + test('rejects private material and stale or incorrect Mobile Key metadata', () => { + const withPrivate = input(); + (withPrivate.mobile as any).xpriv = 'must-never-enter-a-policy-draft'; + expectCode(() => buildRecoverablePolicyReview(withPrivate), 'PRIVATE_MATERIAL'); + + const nestedPrivate = input(); + (nestedPrivate.mobile.origin as any).mnemonic = 'must-never-enter-a-policy-draft'; + expectCode(() => buildRecoverablePolicyReview(nestedPrivate), 'PRIVATE_MATERIAL'); + + const wrongMobilePath = input(); + wrongMobilePath.mobile.origin.bip85Index = 10; + expectCode(() => buildRecoverablePolicyReview(wrongMobilePath), 'INVALID_MOBILE_ORIGIN'); + + const wrongSignerPath = input(); + wrongSignerPath.mobile.derivationPath = "m/48'/0'/0'/2'"; + expectCode(() => buildRecoverablePolicyReview(wrongSignerPath), 'INVALID_DERIVATION'); + }); + + test('rejects duplicate material even when roles differ', () => { + const sameFingerprint = input(); + sameFingerprint.server.masterFingerprint = sameFingerprint.mobile.masterFingerprint; + expectCode(() => buildRecoverablePolicyReview(sameFingerprint), 'DUPLICATE_KEY'); + + const sameXpub = input(); + sameXpub.hardware.xpub = sameXpub.mobile.xpub; + expectCode(() => buildRecoverablePolicyReview(sameXpub), 'DUPLICATE_KEY'); + }); + + test('blocks hardware and transport combinations that cannot verify this policy', () => { + const tapsigner = input(); + tapsigner.hardware.signerType = SignerType.TAPSIGNER; + tapsigner.hardware.origin.device = SignerType.TAPSIGNER; + tapsigner.hardware.origin.transport = 'nfc'; + expect(buildRecoverablePolicyReview(tapsigner).base.total).toBe(3); + expectCode( + () => buildRecoverablePolicyReview({ ...tapsigner, inheritance: inheritance() }), + 'UNSUPPORTED_HARDWARE_POLICY' + ); + const invalidTransport = input(); + invalidTransport.hardware.origin.transport = 'file'; + invalidTransport.hardware.signerType = SignerType.JADE; + invalidTransport.hardware.origin.device = SignerType.JADE; + expectCode(() => buildRecoverablePolicyReview(invalidTransport), 'UNSUPPORTED_HARDWARE'); + }); + + test('requires a future absolute inheritance locktime from supplied chain state', () => { + const draft = input(); + const expired = inheritance(); + expired.activation.value = expired.activation.observedHeight; + expectCode( + () => buildRecoverablePolicyReview({ ...draft, inheritance: expired }), + 'INVALID_ACTIVATION' + ); + + const wrongType = inheritance(); + wrongType.activation.kind = 'median-time-past'; + expectCode( + () => buildRecoverablePolicyReview({ ...draft, inheritance: wrongType }), + 'INVALID_ACTIVATION' + ); + }); +}); diff --git a/tests/services/recoverableMobileKey.test.ts b/tests/services/recoverableMobileKey.test.ts new file mode 100644 index 000000000..629dbcc6a --- /dev/null +++ b/tests/services/recoverableMobileKey.test.ts @@ -0,0 +1,95 @@ +import * as bip39 from 'bip39'; +import BIP32Factory from 'bip32'; +import * as bitcoinJS from 'bitcoinjs-lib'; +import BIP85 from 'src/services/wallets/operations/BIP85'; +import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; +import { + deriveRecoverableMobileKeyPublic, + RECOVERABLE_MOBILE_KEY_INDEX_START, + RECOVERABLE_MOBILE_KEY_MAX_ORDINAL, + RECOVERABLE_MOBILE_KEY_SIGNER_PATH, +} from 'src/services/wallets/operations/recoverable/mobileKey'; + +const RECOVERY_KEY = + 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; +const bip32 = BIP32Factory(ecc); + +describe('Recoverable Wallet Mobile Key derivation', () => { + it('matches the published BIP85 12-word application vector', () => { + const rootXpriv = + 'xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb'; + const entropy = BIP85.bip32XPRVToEntropy("m/83696968'/39'/0'/12'/0'", rootXpriv); + + expect(entropy.subarray(0, 16).toString('hex')).toBe('6250b68daf746d12a24d58b4787a714b'); + expect(BIP85.entropyToBIP39(entropy, 12)).toBe( + 'girl mad pet galaxy egg matter matrix prison refuse sense ordinary nose' + ); + }); + + it('derives a stable testnet signer and records its recovery metadata', async () => { + const first = await deriveRecoverableMobileKeyPublic(RECOVERY_KEY, 0); + const second = await deriveRecoverableMobileKeyPublic(RECOVERY_KEY, 0); + + expect(first).toEqual(second); + expect(first).toMatchObject({ + version: 1, + ordinal: 0, + bip85Index: RECOVERABLE_MOBILE_KEY_INDEX_START, + bip85Path: "m/83696968'/39'/0'/12'/1000000'", + signerPath: RECOVERABLE_MOBILE_KEY_SIGNER_PATH, + network: 'testnet', + }); + expect(first.masterFingerprint).toBe('1C45613D'); + expect(first.xpub).toBe( + 'tpubDEJAyvFpnqeSg7auuzzkG66AUHDeBnbzLbg8aDqBBnf6CMjDmMjkJGeMsHzVtQAizAmEe99D1eQahcbysVbg5M5A9ab7Z2bJNGEBjmzKVVM' + ); + expect(Object.keys(first)).toEqual([ + 'version', + 'ordinal', + 'bip85Index', + 'bip85Path', + 'signerPath', + 'network', + 'masterFingerprint', + 'xpub', + ]); + }); + + it('uses distinct children for different wallets and never reuses hot-wallet child zero', async () => { + const first = await deriveRecoverableMobileKeyPublic(RECOVERY_KEY, 0); + const next = await deriveRecoverableMobileKeyPublic(RECOVERY_KEY, 1); + const hotEntropy = await BIP85.bip39MnemonicToEntropy( + "m/83696968'/39'/0'/12'/0'", + RECOVERY_KEY + ); + const hotMnemonic = BIP85.entropyToBIP39(hotEntropy, 12); + const hotSeed = await bip39.mnemonicToSeed(hotMnemonic); + const hotSigner = bip32 + .fromSeed(hotSeed, bitcoinJS.networks.testnet) + .derivePath(RECOVERABLE_MOBILE_KEY_SIGNER_PATH) + .neutered() + .toBase58(); + + expect(next.bip85Index).toBe(first.bip85Index + 1); + expect(next.xpub).not.toBe(first.xpub); + expect(first.xpub).not.toBe(hotSigner); + }); + + it.each([-1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, RECOVERABLE_MOBILE_KEY_MAX_ORDINAL + 1])( + 'rejects invalid ordinal %s', + async (ordinal) => { + await expect(deriveRecoverableMobileKeyPublic(RECOVERY_KEY, ordinal)).rejects.toThrow( + 'Invalid Recoverable Wallet ordinal' + ); + } + ); + + it('rejects an invalid or non-12-word Recovery Key', async () => { + await expect(deriveRecoverableMobileKeyPublic('abandon'.repeat(12), 0)).rejects.toThrow( + 'A valid 12-word Keeper Recovery Key is required' + ); + await expect( + deriveRecoverableMobileKeyPublic(`${RECOVERY_KEY} ${RECOVERY_KEY}`, 0) + ).rejects.toThrow('A valid 12-word Keeper Recovery Key is required'); + }); +}); diff --git a/tests/services/recoverableMobileKeyOrdinal.test.ts b/tests/services/recoverableMobileKeyOrdinal.test.ts new file mode 100644 index 000000000..10465312b --- /dev/null +++ b/tests/services/recoverableMobileKeyOrdinal.test.ts @@ -0,0 +1,85 @@ +import { + allocateRecoverableMobileKeyOrdinal, + MobileKeyOrdinalLedger, +} from 'src/services/wallets/operations/recoverable/mobileKeyOrdinal'; +import { RECOVERABLE_MOBILE_KEY_MAX_ORDINAL } from 'src/services/wallets/operations/recoverable/mobileKey'; + +const ledger: MobileKeyOrdinalLedger = { + complete: true, + highWaterOrdinal: 2, + records: [ + { walletId: 'first', ordinal: 0, version: 1, state: 'active' }, + { walletId: 'second', ordinal: 1, version: 1, state: 'tombstone' }, + ], + usedOrdinals: [2], +}; + +describe('Recoverable Mobile Key ordinal allocation', () => { + it('allocates after the durable high-water mark, including deleted wallets', () => { + expect( + allocateRecoverableMobileKeyOrdinal(ledger, { kind: 'create', walletId: 'third' }) + ).toEqual({ + kind: 'create', + ordinal: 3, + version: 1, + reservationToPersist: { walletId: 'third', ordinal: 3, version: 1, state: 'reserved' }, + }); + }); + + it('returns the recorded ordinal on restore, including a tombstoned wallet', () => { + expect( + allocateRecoverableMobileKeyOrdinal(ledger, { kind: 'restore', walletId: 'second' }) + ).toEqual({ kind: 'restore', ordinal: 1, version: 1 }); + }); + + it('starts at zero only with a complete empty history', () => { + expect( + allocateRecoverableMobileKeyOrdinal( + { complete: true, highWaterOrdinal: -1, records: [] }, + { kind: 'create', walletId: 'first' } + ) + ).toMatchObject({ ordinal: 0 }); + }); + + it('fails closed for missing history, gaps, ambiguous records or unknown restore', () => { + expect(() => + allocateRecoverableMobileKeyOrdinal( + { ...ledger, complete: false }, + { kind: 'create', walletId: 'x' } + ) + ).toThrow('Complete Mobile Key reservation history is required'); + expect(() => + allocateRecoverableMobileKeyOrdinal( + { ...ledger, usedOrdinals: [] }, + { kind: 'create', walletId: 'x' } + ) + ).toThrow('Incomplete Mobile Key reservation history'); + expect(() => + allocateRecoverableMobileKeyOrdinal( + { + ...ledger, + records: [ + ...ledger.records, + { walletId: 'other', ordinal: 0, version: 1, state: 'active' }, + ], + }, + { kind: 'create', walletId: 'x' } + ) + ).toThrow('Ambiguous Mobile Key reservation history'); + expect(() => + allocateRecoverableMobileKeyOrdinal(ledger, { kind: 'restore', walletId: 'unknown' }) + ).toThrow('Wallet Mobile Key reservation not found'); + expect(() => + allocateRecoverableMobileKeyOrdinal(ledger, { kind: 'create', walletId: 'first' }) + ).toThrow('Wallet ID already has a Mobile Key reservation'); + }); + + it('enforces the reserved ordinal range', () => { + expect(() => + allocateRecoverableMobileKeyOrdinal( + { complete: true, highWaterOrdinal: RECOVERABLE_MOBILE_KEY_MAX_ORDINAL + 1, records: [] }, + { kind: 'create', walletId: 'x' } + ) + ).toThrow('Complete Mobile Key reservation history is required'); + }); +}); From 88803d6a1686bb48e01a3e9a17cdf7fc3671222c Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 15:04:36 +0530 Subject: [PATCH 04/31] Record native packaging limit for updated preview --- docs/preview/recoverable-wallet/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index 4d1fabf78..4b85ea824 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -29,7 +29,7 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr - The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. - Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. -The latest client code passed **57 focused Jest tests** across chooser/navigation, preview isolation, empty-wallet gates, key derivation, policy review, and contact states, plus **17 existing wallet/Recovery Key regression tests**. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. +The latest client code passed **57 focused Jest tests** across chooser/navigation, preview isolation, empty-wallet gates, key derivation, policy review, and contact states, plus **17 existing wallet/Recovery Key regression tests**. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. ## Owner decision (8 October 2026) From 9f259054388bde1743bb1772a9d30b072928afd4 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 15:32:00 +0530 Subject: [PATCH 05/31] Show three wallet choices on empty preview Wallets screen --- docs/preview/recoverable-wallet/README.md | 12 +- .../recoverable-wallet/policy-draft.md | 4 +- .../recoverable-wallet/recovery-contact.md | 4 +- src/components/WalletCreationChooser.tsx | 19 +-- src/navigation/types.ts | 2 +- .../RecoverableWalletPreviewApp.tsx | 72 +++++---- .../AddWalletScreen/WalletChoiceScreen.tsx | 19 ++- src/screens/Home/HomeScreen.tsx | 34 +++- .../Home/components/Wallet/HomeWallet.tsx | 51 +++--- .../recoverable/emptyWalletOnboarding.ts | 11 ++ .../operations/recoverable/mobileKey.ts | 6 +- .../recoverable/mobileKeyConstants.ts | 4 +- .../recoverable/mobileKeyOrdinal.ts | 6 +- .../wallets/recoverable/policyDraft.ts | 74 ++++++--- .../preview/homeScreenEducationGate.test.tsx | 143 +++++++++++++++++ tests/preview/homeWalletLanding.test.tsx | 148 ++++++++++++++++++ .../preview/recoverableWalletScreen.test.tsx | 17 +- tests/preview/walletChoiceScreen.test.tsx | 21 ++- tests/services/emptyWalletOnboarding.test.ts | 22 +++ .../services/recoverable/policyDraft.test.ts | 57 ++++++- 20 files changed, 581 insertions(+), 145 deletions(-) create mode 100644 tests/preview/homeScreenEducationGate.test.tsx create mode 100644 tests/preview/homeWalletLanding.test.tsx diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index 4b85ea824..8140ac553 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -1,6 +1,6 @@ # Recoverable Wallet — parallel Keeper preview -Status (8 October 2026): **isolated client preview and three-choice wallet entry implemented; Android package built for the first checkpoint; iOS package configured but not built**. The latest chooser changes have not yet been packaged in a new APK. This is a simulated walkthrough, not a released or security-reviewed wallet. "Seedless Wallet" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. +Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; Android package built for the earlier checkpoint; iOS package configured but not built**. The revised empty-state chooser has not yet been packaged in a new APK. This is a simulated walkthrough, not a released or security-reviewed wallet. "Seedless Wallet" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. ## First client checkpoint @@ -22,14 +22,14 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr ## Second client checkpoint in this branch -- The separate preview app now starts with **no wallet**. Wallets → Add Wallet opens a reusable full-screen choice of **Simple Wallet** (Hot or Cold next), prominent **Seedless Wallet**, and **Advanced Wallet**; Import Wallet remains visible. Simple, Advanced, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. -- The proposed Mobile Key derives deterministically from the existing 12-word Recovery Key through a dedicated, versioned BIP85 child range starting at index 1,000,000. Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Seedless. The helper returns only testnet public signer details and recovery metadata. The pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. +- The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Simple Wallet** (phone or signing device next), prominent **Seedless Wallet**, and **Advanced Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. Simple, Advanced, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. +- The default Seedless design calls for an independently generated Mobile Key and no new seed words for the user to record. Derivation from Keeper's existing 12-word Recovery Key remains an **optional creation path**, not a setup prerequisite or chooser message. The isolated BIP85 helper reserves a versioned child range starting at index 1,000,000; Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Seedless. Its pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. A Recovery Key cannot recreate a separately generated Mobile Key by derivation alone; that would require a reviewed encrypted backup or wrapping design. - A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. Its 2-of-3 and delayed 2-of-4 results are explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). - A client-only Recovery Contact state model covers encrypted-cloud readback receipts, offline retry, invitation/request expiry, approval/decline, and optional recovery-code gating. It stops before cryptographic enrollment or restoration. No contact key, encrypted backup, native cloud container, or independent exchange channel exists yet. See [recovery-contact.md](recovery-contact.md). - The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. - Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. -The latest client code passed **57 focused Jest tests** across chooser/navigation, preview isolation, empty-wallet gates, key derivation, policy review, and contact states, plus **17 existing wallet/Recovery Key regression tests**. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. +The latest client code passed **70 Jest tests across 12 focused suites** covering the direct empty Wallets entry, Add Wallet chooser, preview isolation, Recovery Key education gate, key-origin policy draft, contact states, and Recovery Key migration. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. ## Owner decision (8 October 2026) @@ -53,7 +53,7 @@ Adam's contribution is welcome, optional, independently reviewed, and must not b - Hardware + Server supports delayed replacement of missing Mobile Key when cloud backup is missing, once server implementation is allowed. - Mobile + Hardware and descriptor support server-independent spending/exit. Test actual external-wallet compatibility; public descriptors do not contain private keys. - Key changes mean new wallet policy and on-chain transfer with fee and original-wallet authorization. Archive the complete predecessor and monitor retained archived addresses indefinitely, including zero-balance wallets. Do not archive merely because the same Mobile Key was restored. -- Keep Recovery Contact distinct from signing keys and Inheritance Key. The existing 12-word Recovery Key is an **additional whole-app recovery route**, not a mandatory prerequisite for this wallet's recovery methods. +- Keep Recovery Contact distinct from signing keys and Inheritance Key. The existing 12-word Recovery Key is an **additional option**, not a mandatory prerequisite or a message on the Seedless choice. Do not imply it can reproduce an independently generated Mobile Key without an encrypted copy or other reviewed recovery mechanism. ## How the owner will test it @@ -61,7 +61,7 @@ Deliver a **separate-installation iOS and Android Keeper Preview** (different ap A new preview checkpoint is complete **only after an installable build and a short device-specific owner test checklist are available**, and after actual tests are recorded: -1. **Prototype/UI**: tap through Add Wallet → recoverable wallet, hardware picker/connection, automatic Mobile/Server status, optional inheritance, one final policy review; include errors/cancel/resume. +1. **Prototype/UI**: start on empty Wallets or use Add Wallet, choose Seedless Wallet, then review hardware picker/connection, automatic Mobile/Server status, optional inheritance, and one final policy; include errors/cancel/resume. 2. **Disposable real wallet**: create fixed 2-of-3 wallet on testnet using supported available signers, safely receive/send test sats, inspect proper fees and outputs. No mainnet, no production credentials. 3. **Backup**: encrypted Mobile Key recovery blob, versioning, iCloud/Drive isolation, read-back verification, retry/offline/background/interrupted write tests; retain existing Keeper backup compatibility. 4. **Recovery via hardware**: lose/reinstall disposable preview, prove hardware possession, restore same wallet and explain retain-versus-rotate Mobile Key after restoration. This requires reviewed server protocol; do not simulate as if implemented. diff --git a/docs/preview/recoverable-wallet/policy-draft.md b/docs/preview/recoverable-wallet/policy-draft.md index 8e96eb25e..f3ab2b5af 100644 --- a/docs/preview/recoverable-wallet/policy-draft.md +++ b/docs/preview/recoverable-wallet/policy-draft.md @@ -2,7 +2,9 @@ `src/services/wallets/recoverable/policyDraft.ts` validates a proposed testnet 2-of-3 Mobile Key + Hardware Key + Server Key arrangement using public metadata only. Optional Inheritance Key is included **before** the whole-policy review. The module never requests a key, creates a wallet, registers a policy, signs, or funds an address. Every result is `fundable: false`. -The Mobile Key metadata must match the version 1 BIP85 reservation from Keeper's Recovery Key, outside the existing hot-wallet and USDT ranges. All signers need a testnet BIP48 native-segwit account tpub with serialized depth 4 and final hardened child index `2'`. Duplicate fingerprints or tpubs, private fields, mainnet keys, and unsupported import transports are rejected. A tpub **cannot prove** its claimed earlier derivation ancestors, master fingerprint, device identity, or possession; those need device-specific checks before wallet creation. +The Mobile Key may have either public origin: `device-generated` (the default Seedless setup path, with an opaque public source reference) or `keeper-recovery-key-bip85` (an optional deterministic recreation path using the version 1 BIP85 reservation outside the existing hot-wallet and USDT ranges). The second origin is valid only when its ordinal, index, and BIP85 path agree. The first origin is **not** deterministically recreatable from Keeper's Recovery Key. Enabling RK-assisted recovery of a device-generated Mobile Key would require a separately designed and verified wrapped-backup protocol; none exists in this draft. The source reference and origin tag cannot prove that native generation, secure storage, or backup occurred. + +All signers need a testnet BIP48 native-segwit account tpub with serialized depth 4 and final hardened child index `2'`. Duplicate fingerprints or tpubs, private fields, mainnet keys, and unsupported import transports are rejected. A tpub **cannot prove** its claimed earlier derivation ancestors, master fingerprint, device identity, or possession; those need device-specific checks before wallet creation. Without Inheritance Key, the review contains Keeper's plain 2-of-3 `VaultScheme`, but no fundable wallet. With Inheritance Key, Keeper's Miniscript policy generator/compiler validates a candidate base 2-of-3 phase and delayed 2-of-4 phase. The review deliberately omits a fundable `MiniscriptScheme` or descriptor. The candidate proves only script compilation and modeled witness paths; it does **not** establish that a particular hardware firmware can display, register, or sign the complete policy. TAPSIGNER, Satochip, and Jade are blocked for this delayed-policy draft because current integrations do not verify the whole policy on-device. Coldcard remains a review candidate, with full hardware-policy compatibility still unproven. The Server Key's genuine public material and registration also remain unavailable until the held server work is reviewed. diff --git a/docs/preview/recoverable-wallet/recovery-contact.md b/docs/preview/recoverable-wallet/recovery-contact.md index d7418f84b..399224bba 100644 --- a/docs/preview/recoverable-wallet/recovery-contact.md +++ b/docs/preview/recoverable-wallet/recovery-contact.md @@ -4,7 +4,7 @@ Status: **state model only**. `src/services/wallets/recoverable/contactRecoveryF ## Proposed independent route -Recovery Contact is distinct from the Inheritance Key, hardware signer, Server Key, and Keeper Recovery Key. The intended route restores only this wallet's derived Mobile Key, plus the wallet descriptor needed to find its funds. It does not reset Keeper or give the contact a signing role. The user must still pair the recovered Mobile Key with another signer to spend. +Recovery Contact is distinct from the Inheritance Key, hardware signer, Server Key, and Keeper Recovery Key. The intended route restores only this wallet's Mobile Key from a separate encrypted backup, plus the wallet descriptor needed to find its funds. It does not reset Keeper or give the contact a signing role. The user must still pair the recovered Mobile Key with another signer to spend. The first security option is access to the user's separate encrypted cloud backup **and** approval from an enrolled contact. A stronger option also requires a user-held recovery code. Both are represented in the state model; neither is selected as a product default yet. The owner must decide whether the extra code is worth its backup burden. With the first option, a malicious contact who also obtains the cloud blob could recover the Mobile Key, though that alone is insufficient for this wallet's 2-of-3 spend. @@ -30,4 +30,4 @@ The request and cloud receipt use a 32-byte public `walletPolicyHash`, not Bitco 4. Build a server-independent QR/share request and response channel with identity checks, approval and decline screens. Confirm the contact cannot silently approve a different wallet or replacement device. 5. Test two devices, both assurance modes, failed cloud readback, expired/replayed messages, lost contact credential, app reinstall, Keeper endpoints blocked, and exact recovered Mobile Key xpub. Obtain independent cryptographic/security review before labeling the path usable. -The fixed Recovery Key-derived Mobile Key creates a separate Recovery Key restore route. If the Recovery Key is available, it can deterministically regenerate the same Mobile Key without contact approval; this contact route is meant for a lost phone when the user cannot or does not want to enter that Recovery Key. Neither route changes the wallet policy by itself. If a key is suspected compromised, rotation still requires a new policy, on-chain transfer, and Archived Wallet handling. +The default Seedless design uses an independently generated Mobile Key. Keeper's Recovery Key cannot derive that same key; any RK-assisted restoration would need a separately designed encrypted copy or wrapping protocol. If the user explicitly chose the optional RK-derived Mobile Key at creation, that Recovery Key can regenerate the same key without contact approval. Neither route changes the wallet policy by itself. If a key is suspected compromised, rotation still requires a new policy, on-chain transfer, and Archived Wallet handling. diff --git a/src/components/WalletCreationChooser.tsx b/src/components/WalletCreationChooser.tsx index 35cd99890..61af48b7c 100644 --- a/src/components/WalletCreationChooser.tsx +++ b/src/components/WalletCreationChooser.tsx @@ -9,7 +9,6 @@ type WalletChoiceCardProps = { icon: string; description: string; eyebrow?: string; - note?: string; highlighted?: boolean; testID: string; onPress: () => void; @@ -47,7 +46,6 @@ export function WalletChoiceCard({ icon, description, eyebrow, - note, highlighted = false, testID, onPress, @@ -118,11 +116,6 @@ export function WalletChoiceCard({ )} {description} - {note && ( - - {note} - - )} ); @@ -145,14 +138,11 @@ export default function WalletCreationChooser({ return ( - - How would you like to hold your bitcoin? - @@ -162,8 +152,7 @@ export default function WalletCreationChooser({ title="Seedless Wallet" icon="✦" eyebrow={seedlessBadge} - description="Mobile + Hardware + Server Key. 2 of 3 keys to spend. No additional wallet seed words to keep." - note="Your Keeper Recovery Key still matters." + description="Phone, hardware, Server Key. Any 2 to spend. No new seed words." highlighted testID="wallet-choice-seedless" onPress={onSeedlessWallet} @@ -179,7 +168,7 @@ export default function WalletCreationChooser({ title="Advanced Wallet" icon="✣" eyebrow="CUSTOM MULTISIG" - description="Custom keys, Miniscript and full control over your wallet policy." + description="Choose your keys and Miniscript rules." testID="wallet-choice-advanced" onPress={onAdvancedWallet} /> @@ -211,7 +200,6 @@ export default function WalletCreationChooser({ const styles = StyleSheet.create({ bodyText: { fontSize: 15, lineHeight: 23 }, chooserSection: { gap: 14, paddingTop: 10 }, - chooserIntro: { marginBottom: 4 }, choiceCard: { borderRadius: 16, padding: 16, gap: 9 }, choiceHeader: { flexDirection: 'row', alignItems: 'center', gap: 11 }, choiceIcon: { @@ -241,6 +229,5 @@ const styles = StyleSheet.create({ importAction: { minHeight: 44, justifyContent: 'center', paddingHorizontal: 6 }, importText: { fontWeight: '600' }, resumeNote: { fontSize: 13, lineHeight: 20, marginTop: -3 }, - note: { fontSize: 13, lineHeight: 20 }, previewNotice: { fontSize: 13, lineHeight: 20, textAlign: 'center' }, }); diff --git a/src/navigation/types.ts b/src/navigation/types.ts index 54ae5209e..e4ffb5ab1 100644 --- a/src/navigation/types.ts +++ b/src/navigation/types.ts @@ -127,7 +127,7 @@ export type AppStackParams = { AssignSignerType: undefined; AddWallet: undefined; AddNewWallet: undefined; - WalletChoice: undefined; + WalletChoice: { initialStage?: 'simple' | 'seedless' } | undefined; CanaryWallets: undefined; AssistedKeys: undefined; SafeKeepingTips: undefined; diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index a469df9a2..c86037a4d 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -187,6 +187,7 @@ function PreviewContent() { warning: dark ? Colors.DeepCharcoalGreen : Colors.dullGreen, }; const [surface, setSurface] = useState('wallets'); + const [choiceOrigin, setChoiceOrigin] = useState<'wallets' | 'chooser'>('wallets'); const [draft, setDraft] = useState(initialPreviewDraft); const [contactEnrollment, setContactEnrollment] = useState(initialContactEnrollment); @@ -199,7 +200,11 @@ function PreviewContent() { const [requestDecision, setRequestDecision] = useState(null); const scrollRef = useRef(null); const act = (action: PreviewAction) => setDraft((current) => reducePreviewDraft(current, action)); - const exitFlow = () => setSurface('chooser'); + const exitFlow = () => setSurface(choiceOrigin); + const openChoice = (choice: PreviewSurface) => { + setChoiceOrigin(surface === 'chooser' ? 'chooser' : 'wallets'); + setSurface(choice); + }; const openRecoveryOptions = () => { setContactEnrollment( reduceContactEnrollment(initialContactEnrollment, { @@ -236,9 +241,9 @@ function PreviewContent() { if (surface === 'cloud' || surface === 'contact') setSurface('recovery'); else if (surface === 'recovery') setSurface('seedless'); else if (surface === 'chooser') setSurface('wallets'); - else if (surface === 'simple') setSurface('chooser'); + else if (surface === 'simple') setSurface(choiceOrigin); else if (surface === 'hot' || surface === 'cold') setSurface('simple'); - else if (surface === 'advanced' || surface === 'import') setSurface('chooser'); + else if (surface === 'advanced' || surface === 'import') setSurface(choiceOrigin); else if (surface === 'seedless' && draft.stage === 'complete') { act({ type: 'RESET' }); exitFlow(); @@ -253,7 +258,7 @@ function PreviewContent() { return true; }); return () => subscription.remove(); - }, [surface, draft.stage]); + }, [surface, draft.stage, choiceOrigin]); useEffect(() => { scrollRef.current?.scrollTo({ y: 0, animated: false }); @@ -262,6 +267,24 @@ function PreviewContent() { const selectedDevice = HARDWARE_CHOICES.find(({ id }) => id === draft.hardware); const hasDraft = draft.stage !== 'automatic' || draft.hardware !== null || draft.inheritanceEnabled; + const walletChooser = (fromWallets: boolean) => ( + openChoice('simple')} + onSeedlessWallet={() => openChoice('seedless')} + onAdvancedWallet={() => openChoice('advanced')} + onImportWallet={() => openChoice('import')} + showSeedless + seedlessBadge={fromWallets ? 'FEATURED' : 'TESTNET PREVIEW'} + previewNotice={ + fromWallets + ? undefined + : 'Simulated choices only. No wallet, key, address, or backup is created in this testnet preview.' + } + seedlessResumeHint={ + hasDraft ? 'Your Seedless Wallet walkthrough will resume where you left off.' : undefined + } + /> + ); return ( @@ -301,46 +324,22 @@ function PreviewContent() { > {surface !== 'chooser' && ( - TESTNET PREVIEW · Simulated walkthrough. No wallet, key, address, cloud backup, or - server registration is created. + {surface === 'wallets' + ? 'TESTNET PREVIEW · Simulated choices. No wallet or key is created.' + : 'TESTNET PREVIEW · Simulated walkthrough. No wallet, key, address, cloud backup, or server registration is created.'} )} {surface === 'wallets' && ( - + No wallets yet - - Choose the wallet setup that suits you. Nothing has been created in this preview. - - setSurface('chooser')} - palette={palette} - /> - - This preview starts without a Hot Wallet. It cannot receive or send bitcoin. - + {walletChooser(true)} )} - {surface === 'chooser' && ( - setSurface('simple')} - onSeedlessWallet={() => setSurface('seedless')} - onAdvancedWallet={() => setSurface('advanced')} - onImportWallet={() => setSurface('import')} - showSeedless - seedlessBadge="TESTNET PREVIEW" - previewNotice="Simulated choices only. No wallet, key, address, or backup is created in this testnet preview." - seedlessResumeHint={ - hasDraft - ? 'Your Seedless Wallet walkthrough will resume where you left off.' - : undefined - } - /> - )} + {surface === 'chooser' && walletChooser(false)} {surface === 'simple' && ( @@ -388,7 +387,7 @@ function PreviewContent() { label="Choose Another" testID="preview-choose-another-wallet" palette={palette} - onPress={() => setSurface('chooser')} + onPress={exitFlow} /> )} @@ -695,8 +694,7 @@ function PreviewContent() { Explore proposed ways to restore this wallet's Mobile Key on another phone. These - paths are separate from Keeper Recovery Key restoration and do not change the wallet - policy. + options do not change the wallet policy. SIMULATED · No Mobile Key, encrypted cloud blob, contact credential, or server diff --git a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx index 279d3ef16..03a313f5f 100644 --- a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx +++ b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx @@ -13,8 +13,9 @@ import { NetworkType } from 'src/services/wallets/enums'; import { isEmptyWalletOnboardingEnabled } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; type ChoiceStage = 'chooser' | 'simple' | 'hot' | 'cold' | 'seedless'; +type WalletChoiceRoute = { params?: { initialStage?: 'simple' | 'seedless' } }; -export default function WalletChoiceScreen() { +export default function WalletChoiceScreen({ route }: { route?: WalletChoiceRoute }) { const navigation = useNavigation(); const { colorMode } = useColorMode(); const network = useAppSelector((state) => state.settings.bitcoinNetworkType); @@ -26,18 +27,28 @@ export default function WalletChoiceScreen() { testnetOnlyFlag: NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY, bundleId: DeviceInfo.getBundleId(), }); - const [stage, setStage] = useState('chooser'); + const initialStage = + route?.params?.initialStage === 'simple' || route?.params?.initialStage === 'seedless' + ? route.params.initialStage + : undefined; + const [stage, setStage] = useState(enabled ? initialStage || 'chooser' : 'chooser'); useEffect(() => { if (!enabled) navigation.goBack(); }, [enabled, navigation]); + useEffect(() => { + if (enabled) setStage(initialStage || 'chooser'); + }, [enabled, initialStage]); + if (!enabled) return null; const back = () => { if (stage === 'hot' || stage === 'cold') setStage('simple'); - else if (stage === 'simple' || stage === 'seedless') setStage('chooser'); - else navigation.goBack(); + else if (stage === 'simple' || stage === 'seedless') { + if (initialStage) navigation.goBack(); + else setStage('chooser'); + } else navigation.goBack(); }; const title = diff --git a/src/screens/Home/HomeScreen.tsx b/src/screens/Home/HomeScreen.tsx index d6846a9e4..3219c344b 100644 --- a/src/screens/Home/HomeScreen.tsx +++ b/src/screens/Home/HomeScreen.tsx @@ -2,8 +2,13 @@ import { StyleSheet, TouchableOpacity } from 'react-native'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import React, { useContext, useEffect, useRef, useState } from 'react'; import useWallets from 'src/hooks/useWallets'; +import useVault from 'src/hooks/useVault'; +import { useUSDTWallets } from 'src/hooks/useUSDTWallets'; import { useAppSelector } from 'src/store/hooks'; -import { NetworkType } from 'src/services/wallets/enums'; +import { NetworkType, VisibilityType } from 'src/services/wallets/enums'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import { shouldDeferRecoveryKeyEducation } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; import useToastMessage from 'src/hooks/useToastMessage'; import { useDispatch } from 'react-redux'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; @@ -38,6 +43,12 @@ function NewHomeScreen({ route }) { const navigation = useNavigation(); const { addedSigner, selectedOption: selectedOptionFromRoute } = route.params || {}; const { wallets } = useWallets({ getAll: true }); + const { allVaults } = useVault({ + includeArchived: false, + getFirst: true, + getHiddenWallets: false, + }); + const { usdtWallets } = useUSDTWallets(); const [electrumErrorVisible, setElectrumErrorVisible] = useState(false); const home_header_circle_background = ThemedColor({ name: 'home_header_circle_background' }); @@ -63,6 +74,20 @@ function NewHomeScreen({ route }) { const recoveryKeyStatus = recoveryKeyStatusByAppId?.[id]; const isConfirmed = recoveryKeyStatus === 'confirmed'; + const hasVisibleWallets = + wallets.some((wallet) => wallet.presentationData.visibility !== VisibilityType.HIDDEN) || + allVaults.length > 0 || + usdtWallets.length > 0; + const deferRecoveryKeyEducation = shouldDeferRecoveryKeyEducation( + { + emptyWalletFlag: NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING, + previewFlag: NativeConfig.KEEPER_PREVIEW, + testnetOnlyFlag: NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY, + bundleId: DeviceInfo.getBundleId(), + }, + bitcoinNetworkType, + hasVisibleWallets + ); const openEducationSheet = () => { setRecoveryKeyFlowState('education'); @@ -77,14 +102,15 @@ function NewHomeScreen({ route }) { // Show education sheet once per session when Recovery Key is not confirmed useEffect(() => { - if (!isConfirmed && !hasShownEducationSheetRef.current) { + if (!deferRecoveryKeyEducation && !isConfirmed && !hasShownEducationSheetRef.current) { openEducationSheet(); } - }, [isConfirmed]); + }, [isConfirmed, deferRecoveryKeyEducation]); useFocusEffect( React.useCallback(() => { if ( + !deferRecoveryKeyEducation && !isConfirmed && !hasShownEducationSheetRef.current && selectedOption !== walletText.more @@ -94,7 +120,7 @@ function NewHomeScreen({ route }) { }, 100); return () => clearTimeout(timer); } - }, [isConfirmed, selectedOption, walletText.more]) + }, [deferRecoveryKeyEducation, isConfirmed, selectedOption, walletText.more]) ); const getContent = () => { diff --git a/src/screens/Home/components/Wallet/HomeWallet.tsx b/src/screens/Home/components/Wallet/HomeWallet.tsx index ad111e1ff..8c56bebf7 100644 --- a/src/screens/Home/components/Wallet/HomeWallet.tsx +++ b/src/screens/Home/components/Wallet/HomeWallet.tsx @@ -3,8 +3,7 @@ import React, { useContext, useState, useEffect } from 'react'; import { FlatList, StyleSheet, TouchableOpacity } from 'react-native'; import NativeConfig from 'react-native-config'; import DeviceInfo from 'react-native-device-info'; -import DashedCta from 'src/components/DashedCta'; -import Buttons from 'src/components/Buttons'; +import WalletCreationChooser from 'src/components/WalletCreationChooser'; import WalletCard from './WalletCard'; import Colors from 'src/theme/Colors'; import useWallets from 'src/hooks/useWallets'; @@ -13,9 +12,9 @@ import { Wallet } from 'src/services/wallets/interfaces/wallet'; import { Vault } from 'src/services/wallets/interfaces/vault'; import useWalletAsset from 'src/hooks/useWalletAsset'; -import { EntityKind, NetworkType, VisibilityType, WalletType } from 'src/services/wallets/enums'; +import { EntityKind, NetworkType, VisibilityType } from 'src/services/wallets/enums'; import { isEmptyWalletOnboardingEnabled } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; -import { useNavigation, useFocusEffect, CommonActions } from '@react-navigation/native'; +import { useNavigation, CommonActions } from '@react-navigation/native'; import KeeperModal from 'src/components/KeeperModal'; import Text from 'src/components/KeeperText'; import { hp, windowWidth, wp } from 'src/constants/responsive'; @@ -27,13 +26,11 @@ import CollaborativeWalletIcon from 'src/assets/images/collaborative_vault_white import { useAppSelector } from 'src/store/hooks'; import { resetCollaborativeSession } from 'src/store/reducers/vaults'; import { useDispatch } from 'react-redux'; -import { autoSyncWallets, refreshWallets } from 'src/store/sagaActions/wallets'; +import { autoSyncWallets } from 'src/store/sagaActions/wallets'; import { RefreshControl } from 'react-native'; import { ELECTRUM_CLIENT } from 'src/services/electrum/client'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; import CircleIconWrapper from 'src/components/CircleIconWrapper'; -import ThemedColor from 'src/components/ThemedColor/ThemedColor'; -import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg'; import { LocalizationContext } from 'src/context/Localization/LocContext'; import BitCoinWalletLogo from 'src/assets/images/bitcoin-wallet-logo.svg'; import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; @@ -49,7 +46,6 @@ import TickIcon from 'src/assets/images/icon_tick.svg'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import Fab from 'src/components/Fab'; import AddIcon from 'src/assets/images/add_white.svg'; -import AddWalletIllustration from 'src/assets/images/addWallet_illustration.svg'; import { useUTXOSpendability } from 'src/hooks/useUTXOSpendability'; import { clearDustToast } from 'src/store/reducers/utxos'; @@ -110,7 +106,6 @@ function WalletCardItem({ const HomeWallet = () => { const { colorMode } = useColorMode(); - const isDarkMode = colorMode === 'dark'; const navigation = useNavigation(); const { wallets } = useWallets({ getAll: true }); const { translations } = useContext(LocalizationContext); @@ -153,15 +148,9 @@ const HomeWallet = () => { bundleId: DeviceInfo.getBundleId(), }); const showWalletEmptyState = usePreviewWalletChooser && allWallets.length === 0; - const openWalletChoice = () => - navigation.dispatch(CommonActions.navigate({ name: 'WalletChoice' })); + const openWalletChoice = (initialStage?: 'simple' | 'seedless') => + navigation.dispatch(CommonActions.navigate({ name: 'WalletChoice', params: { initialStage } })); const [isShowAmount, setIsShowAmount] = useState(false); - const DashedCta_hexagonBackgroundColor = ThemedColor({ - name: 'DashedCta_hexagonBackgroundColor', - }); - const dashed_CTA_background = ThemedColor({ - name: 'dashed_CTA_background', - }); const { showToast } = useToastMessage(); const pendingDustToast = useAppSelector((state: any) => state.utxos.pendingDustToast); @@ -308,14 +297,23 @@ const HomeWallet = () => { ListEmptyComponent={ showWalletEmptyState ? ( - No wallets yet - - Choose how you want to hold your bitcoin. A Hot Wallet has not been created. - - + openWalletChoice('simple')} + onSeedlessWallet={() => openWalletChoice('seedless')} + onAdvancedWallet={() => + navigation.dispatch(CommonActions.navigate({ name: 'AddNewWallet' })) + } + onImportWallet={() => + navigation.dispatch( + CommonActions.navigate({ name: 'VaultConfigurationCreation' }) + ) + } + showSeedless + seedlessBadge="TESTNET PREVIEW" + /> ) : null } @@ -474,13 +472,12 @@ const styles = StyleSheet.create({ gap: 15, }, emptyWalletContainer: { - alignItems: 'center', - paddingTop: hp(30), + paddingTop: hp(10), paddingHorizontal: wp(18), - gap: hp(14), + paddingBottom: hp(28), + gap: hp(8), }, - emptyWalletTitle: { fontSize: 20, textAlign: 'center' }, - emptyWalletBody: { fontSize: 15, lineHeight: 23, textAlign: 'center' }, + emptyWalletTitle: { fontSize: 22 }, addWalletOptionsList: { gap: wp(15), marginBottom: hp(10), diff --git a/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts b/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts index c29dd2561..5ae5a6cf2 100644 --- a/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts +++ b/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts @@ -1,4 +1,5 @@ import { getPreviewRuntime } from 'src/preview/recoverable-wallet/previewRuntime'; +import { NetworkType } from 'src/services/wallets/enums'; export interface EmptyWalletOnboardingGate { emptyWalletFlag?: string; @@ -29,3 +30,13 @@ export const shouldRestoreFallbackMobileWallet = ( hasWalletImages: boolean, hasVaultImages: boolean ): boolean => shouldAutomaticallyCreateMobileWallet(gate) && !hasWalletImages && !hasVaultImages; + +/** Keep the three-choice first-run landing visible until a wallet exists. */ +export const shouldDeferRecoveryKeyEducation = ( + gate: EmptyWalletOnboardingGate, + activeNetwork: NetworkType, + hasVisibleWallets: boolean +): boolean => + !hasVisibleWallets && + activeNetwork === NetworkType.TESTNET && + isEmptyWalletOnboardingEnabled(gate); diff --git a/src/services/wallets/operations/recoverable/mobileKey.ts b/src/services/wallets/operations/recoverable/mobileKey.ts index d1798ec4d..57f94945e 100644 --- a/src/services/wallets/operations/recoverable/mobileKey.ts +++ b/src/services/wallets/operations/recoverable/mobileKey.ts @@ -30,7 +30,11 @@ export interface RecoverableMobileKeyPublic { xpub: string; } -/** Derive public signer details without returning or persisting the child words/private key. */ +/** + * Optional Recovery Key-derived signer path. Seedless setup can instead use an + * independent device-generated Mobile Key and does not need this helper. + * Return only public signer details; never return or persist child words. + */ export const deriveRecoverableMobileKeyPublic = async ( recoveryKey: string, ordinal: number diff --git a/src/services/wallets/operations/recoverable/mobileKeyConstants.ts b/src/services/wallets/operations/recoverable/mobileKeyConstants.ts index 426a14c09..e20ac289e 100644 --- a/src/services/wallets/operations/recoverable/mobileKeyConstants.ts +++ b/src/services/wallets/operations/recoverable/mobileKeyConstants.ts @@ -1,7 +1,7 @@ /** * BIP85 indexes 0–99 belong to Keeper hot wallets/MY_KEEPER signers, and - * 100–199 belong to USDT wallets. Keep this range exclusive to testnet - * Recoverable Wallet Mobile Keys, even when earlier wallets are deleted. + * 100–199 belong to USDT wallets. Keep this range exclusive to the optional + * Recovery Key-derived testnet Mobile Key path, even after wallet deletion. * A future mainnet scheme must receive its own namespace and version. */ export const RECOVERABLE_MOBILE_KEY_INDEX_START = 1_000_000; diff --git a/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts b/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts index 321466676..c09029fee 100644 --- a/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts +++ b/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts @@ -16,7 +16,7 @@ export interface MobileKeyOrdinalReservation { /** Must include every historical reservation, including deleted wallets. */ export interface MobileKeyOrdinalLedger { complete: boolean; - /** Persisted high-water mark; -1 means no Mobile Key has ever been reserved. */ + /** Persisted BIP85 high-water mark; -1 means no derived key has been reserved. */ highWaterOrdinal: number; records: readonly MobileKeyOrdinalReservation[]; /** Optional durable reservations whose wallet record is not available. */ @@ -40,7 +40,9 @@ const isValidOrdinal = (ordinal: number): boolean => Number.isSafeInteger(ordinal) && ordinal >= 0 && ordinal <= RECOVERABLE_MOBILE_KEY_MAX_ORDINAL; /** - * Propose a fresh ordinal from a complete, persisted reservation ledger. + * Propose a fresh ordinal for the optional Recovery Key-derived path from a + * complete, persisted reservation ledger. Device-generated keys use no BIP85 + * ordinal. This allocator is not wired to wallet creation yet. * The caller must atomically persist reservationToPersist before deriving a * new Mobile Key; this pure function does not reserve storage by itself. */ diff --git a/src/services/wallets/recoverable/policyDraft.ts b/src/services/wallets/recoverable/policyDraft.ts index d5483b19e..b5ebe6f31 100644 --- a/src/services/wallets/recoverable/policyDraft.ts +++ b/src/services/wallets/recoverable/policyDraft.ts @@ -39,16 +39,25 @@ export interface RecoverablePublicSignerBase { derivationPath: string; } +export type RecoverableMobileOrigin = + | { + kind: 'device-generated'; + version: 1; + /** Public correlation only. This does not prove that native key generation or backup ran. */ + sourceId: string; + } + | { + kind: 'keeper-recovery-key-bip85'; + version: 1; + ordinal: number; + bip85Index: number; + bip85Path: string; + }; + export interface RecoverableMobileSigner extends RecoverablePublicSignerBase { role: 'mobile'; signerType: SignerType.MOBILE_KEY; - origin: { - kind: 'keeper-recovery-key-bip85'; - version: 1; - ordinal: number; - bip85Index: number; - bip85Path: string; - }; + origin: RecoverableMobileOrigin; } export interface RecoverableHardwareSigner extends RecoverablePublicSignerBase { @@ -208,30 +217,43 @@ function normalizePublicSigner( function validateMobile(signer: RecoverableMobileSigner): RecoverableMobileSigner { const normalized = normalizePublicSigner(signer, 'mobile'); - if (normalized.origin && typeof normalized.origin === 'object') { - assertOnlyKeys( - normalized.origin, - ['kind', 'version', 'ordinal', 'bip85Index', 'bip85Path'], - 'Mobile origin' - ); - } if ( normalized.signerType !== SignerType.MOBILE_KEY || normalized.derivationPath !== MOBILE_KEY_SIGNER_PATH || - normalized.origin?.kind !== 'keeper-recovery-key-bip85' || + !normalized.origin || + typeof normalized.origin !== 'object' || normalized.origin.version !== 1 ) { - fail('INVALID_MOBILE_ORIGIN', 'Mobile Key must use the version 1 Recovery Key derivation'); + fail('INVALID_MOBILE_ORIGIN', 'Mobile Key requires a supported version 1 public origin'); } - const { ordinal, bip85Index, bip85Path } = normalized.origin; - if ( - !Number.isSafeInteger(ordinal) || - ordinal < 0 || - ordinal > MOBILE_KEY_MAX_ORDINAL || - bip85Index !== MOBILE_KEY_BIP85_START + ordinal || - bip85Path !== `m/83696968'/39'/0'/12'/${bip85Index}'` - ) { - fail('INVALID_MOBILE_ORIGIN', 'Mobile Key BIP85 metadata does not match its ordinal'); + + let origin: RecoverableMobileOrigin; + if (normalized.origin.kind === 'device-generated') { + assertOnlyKeys(normalized.origin, ['kind', 'version', 'sourceId'], 'Mobile origin'); + origin = { + kind: 'device-generated', + version: 1, + sourceId: nonEmptyPublicId(normalized.origin.sourceId, 'Mobile source'), + }; + } else if (normalized.origin.kind === 'keeper-recovery-key-bip85') { + assertOnlyKeys( + normalized.origin, + ['kind', 'version', 'ordinal', 'bip85Index', 'bip85Path'], + 'Mobile origin' + ); + const { ordinal, bip85Index, bip85Path } = normalized.origin; + if ( + !Number.isSafeInteger(ordinal) || + ordinal < 0 || + ordinal > MOBILE_KEY_MAX_ORDINAL || + bip85Index !== MOBILE_KEY_BIP85_START + ordinal || + bip85Path !== `m/83696968'/39'/0'/12'/${bip85Index}'` + ) { + fail('INVALID_MOBILE_ORIGIN', 'Mobile Key BIP85 metadata does not match its ordinal'); + } + origin = { kind: 'keeper-recovery-key-bip85', version: 1, ordinal, bip85Index, bip85Path }; + } else { + fail('INVALID_MOBILE_ORIGIN', 'Unsupported Mobile Key public origin'); } return { role: 'mobile', @@ -239,7 +261,7 @@ function validateMobile(signer: RecoverableMobileSigner): RecoverableMobileSigne masterFingerprint: normalized.masterFingerprint, xpub: normalized.xpub, derivationPath: normalized.derivationPath, - origin: { kind: 'keeper-recovery-key-bip85', version: 1, ordinal, bip85Index, bip85Path }, + origin, }; } diff --git a/tests/preview/homeScreenEducationGate.test.tsx b/tests/preview/homeScreenEducationGate.test.tsx new file mode 100644 index 000000000..905757d62 --- /dev/null +++ b/tests/preview/homeScreenEducationGate.test.tsx @@ -0,0 +1,143 @@ +import React from 'react'; +import { render } from '@testing-library/react-native'; +import DeviceInfo from 'react-native-device-info'; +import { useAppSelector } from 'src/store/hooks'; +import useWallets from 'src/hooks/useWallets'; +import { NetworkType, VisibilityType } from 'src/services/wallets/enums'; +import HomeScreen from 'src/screens/Home/HomeScreen'; + +const mockStoreState = { + bhr: { + relayWalletUpdate: null, + relayWalletError: null, + realyWalletErrorMessage: null, + homeToastMessage: null, + }, + account: { recoveryKeyStatusByAppId: {} }, + settings: { bitcoinNetworkType: NetworkType.TESTNET }, +}; + +jest.mock('react-native-config', () => ({ + __esModule: true, + default: { + KEEPER_EMPTY_WALLET_ONBOARDING: 'true', + KEEPER_PREVIEW: 'true', + KEEPER_PREVIEW_TESTNET_ONLY: 'true', + }, +})); +jest.mock('react-native-device-info', () => ({ + __esModule: true, + default: { + getBundleId: jest.fn(), + getVersion: jest.fn(() => '2.5.13'), + getBuildNumber: jest.fn(() => '1'), + }, +})); +jest.mock('@react-navigation/native', () => ({ + useNavigation: () => ({ navigate: jest.fn() }), + useFocusEffect: jest.fn(), +})); +jest.mock('@gluestack-ui/themed-native-base', () => { + const React = require('react'); + const { View } = require('react-native'); + return { + useColorMode: () => ({ colorMode: 'light' }), + Box: ({ children, ...props }) => {children}, + }; +}); +jest.mock('src/store/hooks', () => ({ useAppSelector: jest.fn() })); +jest.mock('react-redux', () => ({ useDispatch: () => jest.fn() })); +jest.mock('src/hooks/useWallets', () => ({ __esModule: true, default: jest.fn() })); +jest.mock('src/hooks/useVault', () => ({ + __esModule: true, + default: () => ({ allVaults: [] }), +})); +jest.mock('src/hooks/useUSDTWallets', () => ({ + useUSDTWallets: () => ({ usdtWallets: [] }), +})); +jest.mock('src/hooks/useToastMessage', () => ({ + __esModule: true, + default: () => ({ showToast: jest.fn() }), +})); +jest.mock('@realm/react', () => ({ useQuery: () => [] })); +jest.mock('src/storage/realm/dbManager', () => ({ + __esModule: true, + default: { getObjectByIndex: () => ({ id: 'app-id' }) }, +})); +jest.mock('src/context/Localization/LocContext', () => { + const React = require('react'); + return { + LocalizationContext: React.createContext({ + translations: { + home: { educationSheetTitle: 'Recovery Key education' }, + wallet: { homeWallets: 'Wallets', keys: 'Keys', more: 'More' }, + buyBTC: { acquire: 'Buy' }, + askAi: { ask: 'Ask' }, + }, + }), + }; +}); +jest.mock('src/services/sentry', () => ({ SentryErrorBoundary: (Component) => Component })); +jest.mock('src/components/KeeperModal', () => { + const { Text, View } = require('react-native'); + return ({ visible, title }) => + visible ? ( + + {title} + + ) : null; +}); +jest.mock('src/components/KeeperText', () => { + const React = require('react'); + const { Text } = require('react-native'); + return ({ children, ...props }) => {children}; +}); +jest.mock('src/screens/Home/InititalAppController', () => () => null); +jest.mock('src/screens/Home/components/Wallet/HomeWallet', () => () => null); +jest.mock('src/screens/Home/components/Keys/ManageKeys', () => () => null); +jest.mock('src/screens/Home/components/Settings/keeperSettings', () => () => null); +jest.mock('src/screens/Home/components/buyBtc/BuyBtc', () => () => null); +jest.mock('src/screens/HelpAi/HelpAiEntry', () => () => null); +jest.mock('src/components/HomeScreenHeader', () => () => null); +jest.mock('src/components/MenuFooter', () => () => null); +jest.mock('src/components/CircleIconWrapper', () => () => null); +jest.mock('src/components/ThemedColor/ThemedColor', () => () => 'green'); + +describe('first-run Recovery Key education sheet', () => { + beforeEach(() => { + jest.clearAllMocks(); + (useAppSelector as jest.Mock).mockImplementation((selector) => selector(mockStoreState)); + (useWallets as jest.Mock).mockReturnValue({ wallets: [] }); + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + mockStoreState.settings.bitcoinNetworkType = NetworkType.TESTNET; + }); + + it('leaves the empty preview Wallets landing unobscured', () => { + const screen = render(); + expect(screen.queryByText('Recovery Key education')).toBeNull(); + }); + + it('preserves education when a wallet exists or the app is production', () => { + (useWallets as jest.Mock).mockReturnValue({ + wallets: [{ presentationData: { visibility: VisibilityType.DEFAULT } }], + }); + const withWallet = render(); + expect(withWallet.getByText('Recovery Key education')).toBeTruthy(); + withWallet.unmount(); + + (useWallets as jest.Mock).mockReturnValue({ wallets: [] }); + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue('io.hexawallet.keeper'); + const production = render(); + expect(production.getByText('Recovery Key education')).toBeTruthy(); + production.unmount(); + + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + mockStoreState.settings.bitcoinNetworkType = NetworkType.MAINNET; + const mainnet = render(); + expect(mainnet.getByText('Recovery Key education')).toBeTruthy(); + }); +}); diff --git a/tests/preview/homeWalletLanding.test.tsx b/tests/preview/homeWalletLanding.test.tsx new file mode 100644 index 000000000..cb323ba82 --- /dev/null +++ b/tests/preview/homeWalletLanding.test.tsx @@ -0,0 +1,148 @@ +import React from 'react'; +import { fireEvent, render } from '@testing-library/react-native'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import { useAppSelector } from 'src/store/hooks'; +import useWallets from 'src/hooks/useWallets'; +import { NetworkType } from 'src/services/wallets/enums'; +import HomeWallet from 'src/screens/Home/components/Wallet/HomeWallet'; + +const mockNavigate = jest.fn(); +const mockDispatch = jest.fn(); +const mockCommonNavigate = jest.fn(({ name, params }) => ({ type: 'NAVIGATE', name, params })); +const mockStoreState = { + vault: { collaborativeSession: { signers: {} } }, + settings: { bitcoinNetworkType: NetworkType.TESTNET }, + wallet: { walletSyncing: {} }, + utxos: { pendingDustToast: null }, +}; + +jest.mock('react-native-config', () => ({ + __esModule: true, + default: { + KEEPER_EMPTY_WALLET_ONBOARDING: 'true', + KEEPER_PREVIEW: 'true', + KEEPER_PREVIEW_TESTNET_ONLY: 'true', + }, +})); +jest.mock('react-native-device-info', () => ({ + __esModule: true, + default: { + getBundleId: jest.fn(), + getVersion: jest.fn(() => '2.5.13'), + getBuildNumber: jest.fn(() => '1'), + }, +})); +jest.mock('@react-navigation/native', () => ({ + useNavigation: () => ({ navigate: mockNavigate, dispatch: mockDispatch }), + CommonActions: { navigate: (route) => mockCommonNavigate(route) }, + useFocusEffect: jest.fn(), +})); +jest.mock('@gluestack-ui/themed-native-base', () => { + const React = require('react'); + const { View } = require('react-native'); + return { + useColorMode: () => ({ colorMode: 'light' }), + Box: ({ children, ...props }) => {children}, + View: ({ children, ...props }) => {children}, + }; +}); +jest.mock('src/store/hooks', () => ({ useAppSelector: jest.fn() })); +jest.mock('src/store/reducers/vaults', () => ({ resetCollaborativeSession: jest.fn() })); +jest.mock('src/store/reducers/utxos', () => ({ clearDustToast: jest.fn() })); +jest.mock('react-redux', () => ({ useDispatch: () => jest.fn() })); +jest.mock('src/hooks/useWallets', () => ({ + __esModule: true, + default: jest.fn(() => ({ wallets: [] })), +})); +jest.mock('src/hooks/useVault', () => ({ __esModule: true, default: () => ({ allVaults: [] }) })); +jest.mock('src/hooks/useUSDTWallets', () => ({ + useUSDTWallets: () => ({ usdtWallets: [], createWallet: jest.fn() }), +})); +jest.mock('src/hooks/useWalletAsset', () => ({ + __esModule: true, + default: () => ({ getWalletCardGradient: jest.fn(), getWalletTags: jest.fn() }), +})); +jest.mock('src/hooks/useUTXOSpendability', () => ({ + useUTXOSpendability: () => ({ hasDoNotSpendUTXOs: false }), +})); +jest.mock('src/hooks/useToastMessage', () => ({ + __esModule: true, + default: () => ({ showToast: jest.fn() }), +})); +jest.mock('src/services/electrum/client', () => ({ + ELECTRUM_CLIENT: { isClientConnected: false }, +})); +jest.mock('src/services/wallets/factories/USDTWalletFactory', () => ({ + USDTWalletSupportedNetwork: 'MAINNET', + USDTWalletType: { IMPORTED: 'IMPORTED' }, + getAvailableBalanceUSDTWallet: jest.fn(), +})); +jest.mock('src/components/KeeperModal', () => () => null); +jest.mock('src/components/AppActivityIndicator/ActivityIndicatorView', () => () => null); +jest.mock('src/components/Fab', () => () => null); +jest.mock('src/screens/Home/components/Wallet/WalletCard', () => () => null); +jest.mock('src/components/ThemedColor/ThemedColor', () => () => 'green'); +jest.mock('src/context/Localization/LocContext', () => { + const React = require('react'); + return { + LocalizationContext: React.createContext({ + translations: { wallet: {}, home: {}, common: {}, usdtWalletText: {} }, + }), + }; +}); +jest.mock('src/components/KeeperText', () => { + const React = require('react'); + const { Text } = require('react-native'); + return ({ children, ...props }) => {children}; +}); + +describe('first-run Wallets landing', () => { + beforeEach(() => { + jest.clearAllMocks(); + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + (useAppSelector as jest.Mock).mockImplementation((selector) => selector(mockStoreState)); + (useWallets as jest.Mock).mockReturnValue({ wallets: [] }); + NativeConfig.KEEPER_EMPTY_WALLET_ONBOARDING = 'true'; + mockStoreState.settings.bitcoinNetworkType = NetworkType.TESTNET; + }); + + it('shows the three choices directly and routes the selected choice', () => { + const screen = render(); + expect(screen.getByTestId('wallets-empty-state')).toBeTruthy(); + expect(screen.getByTestId('wallet-choice-simple')).toBeTruthy(); + expect(screen.getByTestId('wallet-choice-seedless')).toBeTruthy(); + expect(screen.getByTestId('wallet-choice-advanced')).toBeTruthy(); + + fireEvent.press(screen.getByTestId('wallet-choice-simple')); + expect(mockCommonNavigate).toHaveBeenCalledWith({ + name: 'WalletChoice', + params: { initialStage: 'simple' }, + }); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(mockCommonNavigate).toHaveBeenCalledWith({ + name: 'WalletChoice', + params: { initialStage: 'seedless' }, + }); + fireEvent.press(screen.getByTestId('wallet-choice-advanced')); + expect(mockCommonNavigate).toHaveBeenCalledWith({ name: 'AddNewWallet' }); + fireEvent.press(screen.getByTestId('wallet-choice-import')); + expect(mockCommonNavigate).toHaveBeenCalledWith({ name: 'VaultConfigurationCreation' }); + }); + + it('keeps the production and mainnet landing unchanged', () => { + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue('io.hexawallet.keeper'); + const production = render(); + expect(production.queryByTestId('wallet-creation-chooser')).toBeNull(); + production.unmount(); + + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue( + 'io.hexawallet.keeper.recoverablepreview' + ); + mockStoreState.settings.bitcoinNetworkType = NetworkType.MAINNET; + const mainnet = render(); + expect(mainnet.queryByTestId('wallet-creation-chooser')).toBeNull(); + }); +}); diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index 136c64d2d..dc0db5dd9 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -27,7 +27,6 @@ jest.mock('src/components/KeeperText', () => { }); function enterRecoveryOptions(screen) { - fireEvent.press(screen.getByTestId('primary-Add Wallet')); fireEvent.press(screen.getByTestId('wallet-choice-seedless')); fireEvent.press(screen.getByTestId('primary-Continue')); fireEvent.press(screen.getByTestId('preview-hardware-Coldcard')); @@ -48,8 +47,8 @@ describe('Recoverable Wallet preview on a small screen', () => { test('keeps security copy available, reaches one final review, and resumes after cancel', () => { const screen = render(); - expect(screen.getByTestId('preview-add-wallet')).toHaveTextContent('No wallets yet'); - fireEvent.press(screen.getByTestId('primary-Add Wallet')); + expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('No wallets yet'); + expect(screen.queryByTestId('primary-Add Wallet')).toBeNull(); fireEvent.press(screen.getByTestId('wallet-choice-seedless')); expect(screen.getByTestId('preview-simulation-banner')).toHaveTextContent( 'Simulated walkthrough' @@ -88,17 +87,20 @@ describe('Recoverable Wallet preview on a small screen', () => { fireEvent.press(screen.getByTestId('primary-Finish Preview')); expect(screen.getByTestId('preview-complete')).toHaveTextContent('No wallet was created'); fireEvent.press(screen.getByTestId('preview-done')); - expect(screen.getByTestId('wallet-creation-chooser')).toBeTruthy(); + expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('Seedless Wallet'); }); test('navigates the three-choice entry and keeps other paths simulated', () => { const screen = render(); - fireEvent.press(screen.getByTestId('primary-Add Wallet')); const chooser = screen.getByTestId('wallet-creation-chooser'); expect(chooser).toHaveTextContent('Simple Wallet'); expect(chooser).toHaveTextContent('Seedless Wallet'); expect(chooser).toHaveTextContent('Advanced Wallet'); - expect(chooser).toHaveTextContent('Your Keeper Recovery Key still matters'); + expect(chooser).toHaveTextContent('On this phone or a signing device'); + expect(chooser).toHaveTextContent('Any 2 to spend. No new seed words.'); + expect(chooser).not.toHaveTextContent('Recovery Key'); + expect(chooser).not.toHaveTextContent('How would you like to hold your bitcoin?'); + expect(chooser).toHaveTextContent('FEATURED'); const seedlessTitle = screen.getByText('Seedless Wallet'); expect(seedlessTitle.props.allowFontScaling).toBe(true); expect(seedlessTitle.props.numberOfLines).toBeUndefined(); @@ -124,8 +126,7 @@ describe('Recoverable Wallet preview on a small screen', () => { 'No existing wallet or key was accessed' ); fireEvent.press(screen.getByTestId('preview-back')); - fireEvent.press(screen.getByTestId('preview-back')); - expect(screen.getByTestId('preview-add-wallet')).toHaveTextContent('No wallets yet'); + expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('No wallets yet'); }); test('the shared chooser hides Seedless Wallet unless the caller explicitly enables it', () => { diff --git a/tests/preview/walletChoiceScreen.test.tsx b/tests/preview/walletChoiceScreen.test.tsx index dcd7f4a92..f12533efd 100644 --- a/tests/preview/walletChoiceScreen.test.tsx +++ b/tests/preview/walletChoiceScreen.test.tsx @@ -79,9 +79,28 @@ describe('guarded Wallets chooser route', () => { test('fails closed if the active network is not testnet', () => { (useAppSelector as jest.Mock).mockReturnValue(NetworkType.MAINNET); - const screen = render(); + const screen = render(); expect(screen.queryByTestId('wallet-creation-chooser')).toBeNull(); + expect(screen.queryByTestId('wallet-choice-seedless-unavailable')).toBeNull(); + expect(mockNavigation.goBack).toHaveBeenCalledTimes(1); + }); + + test('opens a direct empty-state choice and returns to Wallets on Back', () => { + const simple = render(); + expect(simple.getByTestId('wallet-choice-simple-options')).toHaveTextContent('Hot Wallet'); + expect(simple.queryByTestId('wallet-creation-chooser')).toBeNull(); + fireEvent.press(simple.getByTestId('wallet-choice-back')); expect(mockNavigation.goBack).toHaveBeenCalledTimes(1); + simple.unmount(); + + const seedless = render( + + ); + expect(seedless.getByTestId('wallet-choice-seedless-unavailable')).toHaveTextContent( + 'separate Keeper Preview app' + ); + fireEvent.press(seedless.getByTestId('wallet-choice-back')); + expect(mockNavigation.goBack).toHaveBeenCalledTimes(2); }); test('offers guarded choices without opening an unverified Seedless or Simple flow', () => { diff --git a/tests/services/emptyWalletOnboarding.test.ts b/tests/services/emptyWalletOnboarding.test.ts index 2a8467e02..5857b7798 100644 --- a/tests/services/emptyWalletOnboarding.test.ts +++ b/tests/services/emptyWalletOnboarding.test.ts @@ -1,8 +1,10 @@ import { isEmptyWalletOnboardingEnabled, shouldAutomaticallyCreateMobileWallet, + shouldDeferRecoveryKeyEducation, shouldRestoreFallbackMobileWallet, } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; +import { NetworkType } from 'src/services/wallets/enums'; const previewGate = { emptyWalletFlag: 'true', @@ -60,4 +62,24 @@ describe('empty Wallet onboarding gate', () => { shouldRestoreFallbackMobileWallet({ ...previewGate, emptyWalletFlag: undefined }, false, true) ).toBe(false); }); + + it('defers the Recovery Key sheet only on the empty testnet preview landing', () => { + expect(shouldDeferRecoveryKeyEducation(previewGate, NetworkType.TESTNET, false)).toBe(true); + expect(shouldDeferRecoveryKeyEducation(previewGate, NetworkType.TESTNET, true)).toBe(false); + expect(shouldDeferRecoveryKeyEducation(previewGate, NetworkType.MAINNET, false)).toBe(false); + expect( + shouldDeferRecoveryKeyEducation( + { ...previewGate, bundleId: 'io.hexawallet.keeper' }, + NetworkType.TESTNET, + false + ) + ).toBe(false); + expect( + shouldDeferRecoveryKeyEducation( + { ...previewGate, emptyWalletFlag: undefined }, + NetworkType.TESTNET, + false + ) + ).toBe(false); + }); }); diff --git a/tests/services/recoverable/policyDraft.test.ts b/tests/services/recoverable/policyDraft.test.ts index d13dba1f8..a3167a043 100644 --- a/tests/services/recoverable/policyDraft.test.ts +++ b/tests/services/recoverable/policyDraft.test.ts @@ -31,11 +31,9 @@ function input(): RecoverablePolicyDraftInput { signerType: SignerType.MOBILE_KEY, ...publicKeyFor(1), origin: { - kind: 'keeper-recovery-key-bip85', + kind: 'device-generated', version: 1, - ordinal: 0, - bip85Index: 1_000_000, - bip85Path: "m/83696968'/39'/0'/12'/1000000'", + sourceId: 'preview-device-mobile-key-1', }, }; const hardware: RecoverableHardwareSigner = { @@ -58,6 +56,18 @@ function input(): RecoverablePolicyDraftInput { return { version: 1, network: NetworkType.TESTNET, mobile, hardware, server }; } +function inputWithRecoveryKeyOrigin(): RecoverablePolicyDraftInput { + const draft = input(); + draft.mobile.origin = { + kind: 'keeper-recovery-key-bip85', + version: 1, + ordinal: 0, + bip85Index: 1_000_000, + bip85Path: "m/83696968'/39'/0'/12'/1000000'", + }; + return draft; +} + function inheritance(): RecoverableInheritanceChoice { return { signer: { @@ -107,9 +117,26 @@ describe('public Recoverable Wallet policy draft', () => { multisigScriptType: MultisigScriptType.DEFAULT_MULTISIG, }); expect(review.candidateMiniscript).toBeNull(); + expect(review.base.signers[0].origin).toEqual({ + kind: 'device-generated', + version: 1, + sourceId: 'preview-device-mobile-key-1', + }); expect(JSON.stringify(review)).not.toMatch(/xpriv|mnemonic|recoveryKey/i); }); + test('accepts explicit optional Recovery Key derivation metadata without requiring it', () => { + const review = buildRecoverablePolicyReview(inputWithRecoveryKeyOrigin()); + expect(review.base.signers[0].origin).toEqual({ + kind: 'keeper-recovery-key-bip85', + version: 1, + ordinal: 0, + bip85Index: 1_000_000, + bip85Path: "m/83696968'/39'/0'/12'/1000000'", + }); + expect(review.fundable).toBe(false); + }); + test('compiles an optional delayed 2-of-4 candidate before final policy review', () => { const review = buildRecoverablePolicyReview({ ...input(), inheritance: inheritance() }); const scheme = review.candidateMiniscript; @@ -157,7 +184,7 @@ describe('public Recoverable Wallet policy draft', () => { expectCode(() => buildRecoverablePolicyReview(wrongChild), 'INVALID_XPUB_ORIGIN'); }); - test('rejects private material and stale or incorrect Mobile Key metadata', () => { + test('rejects private material and malformed Mobile Key origin metadata', () => { const withPrivate = input(); (withPrivate.mobile as any).xpriv = 'must-never-enter-a-policy-draft'; expectCode(() => buildRecoverablePolicyReview(withPrivate), 'PRIVATE_MATERIAL'); @@ -166,10 +193,26 @@ describe('public Recoverable Wallet policy draft', () => { (nestedPrivate.mobile.origin as any).mnemonic = 'must-never-enter-a-policy-draft'; expectCode(() => buildRecoverablePolicyReview(nestedPrivate), 'PRIVATE_MATERIAL'); - const wrongMobilePath = input(); - wrongMobilePath.mobile.origin.bip85Index = 10; + const missingGeneratedSource = input(); + missingGeneratedSource.mobile.origin = { + kind: 'device-generated', + version: 1, + sourceId: ' ', + }; + expectCode(() => buildRecoverablePolicyReview(missingGeneratedSource), 'INVALID_ORIGIN'); + + const inventedRecoveryClaim = input(); + (inventedRecoveryClaim.mobile.origin as any).bip85Index = 1_000_000; + expectCode(() => buildRecoverablePolicyReview(inventedRecoveryClaim), 'UNEXPECTED_FIELD'); + + const wrongMobilePath = inputWithRecoveryKeyOrigin(); + (wrongMobilePath.mobile.origin as any).bip85Index = 10; expectCode(() => buildRecoverablePolicyReview(wrongMobilePath), 'INVALID_MOBILE_ORIGIN'); + const unsupportedOrigin = input(); + (unsupportedOrigin.mobile.origin as any).kind = 'unknown'; + expectCode(() => buildRecoverablePolicyReview(unsupportedOrigin), 'INVALID_MOBILE_ORIGIN'); + const wrongSignerPath = input(); wrongSignerPath.mobile.derivationPath = "m/48'/0'/0'/2'"; expectCode(() => buildRecoverablePolicyReview(wrongSignerPath), 'INVALID_DERIVATION'); From 87a873d03dc438a658be77a56d1c8488eb94d164 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 15:42:54 +0530 Subject: [PATCH 06/31] Clarify wallet choice names and seedless preview copy --- docs/preview/recoverable-wallet/README.md | 2 +- src/components/WalletCreationChooser.tsx | 15 +++++---------- .../RecoverableWalletPreviewApp.tsx | 17 ++++++++--------- .../AddWalletScreen/WalletChoiceScreen.tsx | 6 +++--- .../Home/components/Wallet/HomeWallet.tsx | 2 +- tests/preview/recoverableWalletScreen.test.tsx | 17 +++++++++++------ 6 files changed, 29 insertions(+), 30 deletions(-) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index 8140ac553..c96a6be55 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -22,7 +22,7 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr ## Second client checkpoint in this branch -- The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Simple Wallet** (phone or signing device next), prominent **Seedless Wallet**, and **Advanced Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. Simple, Advanced, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. +- The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Single-Key Wallet** (phone or signing device next), prominent **Seedless Wallet**, and **Custom Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. The labels describe setup paths, without a “Featured” badge or a blanket seed-word promise on the card. Single-Key, Custom, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. - The default Seedless design calls for an independently generated Mobile Key and no new seed words for the user to record. Derivation from Keeper's existing 12-word Recovery Key remains an **optional creation path**, not a setup prerequisite or chooser message. The isolated BIP85 helper reserves a versioned child range starting at index 1,000,000; Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Seedless. Its pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. A Recovery Key cannot recreate a separately generated Mobile Key by derivation alone; that would require a reviewed encrypted backup or wrapping design. - A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. Its 2-of-3 and delayed 2-of-4 results are explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). - A client-only Recovery Contact state model covers encrypted-cloud readback receipts, offline retry, invitation/request expiry, approval/decline, and optional recovery-code gating. It stops before cryptographic enrollment or restoration. No contact key, encrypted backup, native cloud container, or independent exchange channel exists yet. See [recovery-contact.md](recovery-contact.md). diff --git a/src/components/WalletCreationChooser.tsx b/src/components/WalletCreationChooser.tsx index 61af48b7c..af17749d4 100644 --- a/src/components/WalletCreationChooser.tsx +++ b/src/components/WalletCreationChooser.tsx @@ -20,7 +20,6 @@ export type WalletCreationChooserProps = { onAdvancedWallet: () => void; onImportWallet?: () => void; showSeedless?: boolean; - seedlessBadge?: string; seedlessResumeHint?: string; previewNotice?: string; }; @@ -127,7 +126,6 @@ export default function WalletCreationChooser({ onAdvancedWallet, onImportWallet, showSeedless = false, - seedlessBadge, seedlessResumeHint, previewNotice, }: WalletCreationChooserProps) { @@ -139,10 +137,9 @@ export default function WalletCreationChooser({ return ( @@ -151,8 +148,7 @@ export default function WalletCreationChooser({ )} diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index c86037a4d..cd0d9dac5 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -274,11 +274,10 @@ function PreviewContent() { onAdvancedWallet={() => openChoice('advanced')} onImportWallet={() => openChoice('import')} showSeedless - seedlessBadge={fromWallets ? 'FEATURED' : 'TESTNET PREVIEW'} previewNotice={ fromWallets ? undefined - : 'Simulated choices only. No wallet, key, address, or backup is created in this testnet preview.' + : 'TESTNET PREVIEW · Simulated choices. No wallet, key, address, or backup is created.' } seedlessResumeHint={ hasDraft ? 'Your Seedless Wallet walkthrough will resume where you left off.' : undefined @@ -295,13 +294,13 @@ function PreviewContent() { : surface === 'chooser' ? 'Choose a Wallet' : surface === 'simple' - ? 'Simple Wallet' + ? 'Single-Key Wallet' : surface === 'hot' ? 'Hot Wallet' : surface === 'cold' ? 'Cold Wallet' : surface === 'advanced' - ? 'Advanced Wallet' + ? 'Custom Wallet' : surface === 'import' ? 'Import Wallet' : surface === 'recovery' @@ -380,8 +379,8 @@ function PreviewContent() { : 'A Cold Wallet would use one external signing key. No device is connected or registered here.'} - SIMULATED CHOICE · Simple Wallet creation is not available in this preview. No wallet, - address, or backup exists. + SIMULATED CHOICE · Single-Key Wallet creation is not available in this preview. No + wallet, address, or backup exists. - Custom multisig + Custom setup - Advanced Wallet is for choosing your keys and spending rules, including Miniscript + Custom Wallet is for choosing your keys and spending rules, including Miniscript options such as Inheritance Key, Emergency Key, and Wallet Timelock. - PREVIEW ONLY · Advanced Wallet creation is not connected in this isolated app. No + PREVIEW ONLY · Custom Wallet creation is not connected in this isolated app. No policy, key, or wallet is created. diff --git a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx index 03a313f5f..bae49a88f 100644 --- a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx +++ b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx @@ -55,7 +55,7 @@ export default function WalletChoiceScreen({ route }: { route?: WalletChoiceRout stage === 'chooser' ? 'Choose a Wallet' : stage === 'simple' - ? 'Simple Wallet' + ? 'Single-Key Wallet' : stage === 'hot' ? 'Hot Wallet' : stage === 'cold' @@ -73,13 +73,13 @@ export default function WalletChoiceScreen({ route }: { route?: WalletChoiceRout onAdvancedWallet={() => navigation.navigate('AddNewWallet')} onImportWallet={() => navigation.navigate('VaultConfigurationCreation')} showSeedless - seedlessBadge="TESTNET PREVIEW" + previewNotice="TESTNET PREVIEW · Seedless setup is simulated; no Seedless Wallet is created." /> )} {stage === 'simple' && ( - A Simple Wallet uses one key to spend. Choose where that key would be held. + Choose where you want to hold the key. { ) } showSeedless - seedlessBadge="TESTNET PREVIEW" + previewNotice="TESTNET PREVIEW · Seedless setup is simulated; no Seedless Wallet is created." /> ) : null diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index dc0db5dd9..0b2a5e219 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -93,14 +93,19 @@ describe('Recoverable Wallet preview on a small screen', () => { test('navigates the three-choice entry and keeps other paths simulated', () => { const screen = render(); const chooser = screen.getByTestId('wallet-creation-chooser'); - expect(chooser).toHaveTextContent('Simple Wallet'); + expect(chooser).toHaveTextContent('Single-Key Wallet'); expect(chooser).toHaveTextContent('Seedless Wallet'); - expect(chooser).toHaveTextContent('Advanced Wallet'); - expect(chooser).toHaveTextContent('On this phone or a signing device'); - expect(chooser).toHaveTextContent('Any 2 to spend. No new seed words.'); + expect(chooser).toHaveTextContent('Custom Wallet'); + expect(chooser).toHaveTextContent('Use your phone or a signing device.'); + expect(chooser).toHaveTextContent( + 'Phone, compatible hardware and Server Key. 2 of 3 keys to spend.' + ); + expect(chooser).toHaveTextContent('Choose your keys and spending rules.'); expect(chooser).not.toHaveTextContent('Recovery Key'); expect(chooser).not.toHaveTextContent('How would you like to hold your bitcoin?'); - expect(chooser).toHaveTextContent('FEATURED'); + expect(chooser).not.toHaveTextContent('FEATURED'); + expect(chooser).not.toHaveTextContent('SINGLE KEY'); + expect(chooser).not.toHaveTextContent('CUSTOM MULTISIG'); const seedlessTitle = screen.getByText('Seedless Wallet'); expect(seedlessTitle.props.allowFontScaling).toBe(true); expect(seedlessTitle.props.numberOfLines).toBeUndefined(); @@ -118,7 +123,7 @@ describe('Recoverable Wallet preview on a small screen', () => { fireEvent.press(screen.getByTestId('wallet-choice-advanced')); expect(screen.getByTestId('preview-advanced-wallet')).toHaveTextContent( - 'Advanced Wallet creation is not connected' + 'Custom Wallet creation is not connected' ); fireEvent.press(screen.getByTestId('preview-back')); fireEvent.press(screen.getByTestId('wallet-choice-import')); From a99f8f2905e189fba3289ad76ffd49066f5918ed Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 15:43:52 +0530 Subject: [PATCH 07/31] Explain seedless backup boundary after wallet choice --- .../recoverable-wallet/RecoverableWalletPreviewApp.tsx | 4 ++++ tests/preview/recoverableWalletScreen.test.tsx | 3 +++ 2 files changed, 7 insertions(+) diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index cd0d9dac5..401e1288d 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -431,6 +431,10 @@ function PreviewContent() { The proposed wallet needs 2 of 3 keys to spend. These statuses demonstrate the intended automatic setup. No key material has been generated. + + In the proposed setup, you would not write down seed words for this wallet. Your + signing device may have its own backup steps. + Mobile Key diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index 0b2a5e219..cdd77d02c 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -56,6 +56,9 @@ describe('Recoverable Wallet preview on a small screen', () => { expect(screen.getByTestId('preview-automatic')).toHaveTextContent( 'No key material has been generated' ); + expect(screen.getByTestId('preview-automatic')).toHaveTextContent( + 'Your signing device may have its own backup steps.' + ); const serverWarning = screen.getByText(/Keeper cannot spend your bitcoin with this key alone/); expect(serverWarning.props.allowFontScaling).toBe(true); expect(StyleSheet.flatten(serverWarning.props.style).lineHeight).toBeGreaterThan(23); From fa70b38237125e763f4c81690f54d94543cb79a6 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 16:00:09 +0530 Subject: [PATCH 08/31] Show simulated Seedless key progress before hardware choice --- docs/preview/recoverable-wallet/README.md | 3 +- .../RecoverableWalletPreviewApp.tsx | 175 ++++++++++++++---- .../preview/recoverableWalletScreen.test.tsx | 76 +++++++- 3 files changed, 207 insertions(+), 47 deletions(-) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index c96a6be55..b74d4c11d 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -23,13 +23,14 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr ## Second client checkpoint in this branch - The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Single-Key Wallet** (phone or signing device next), prominent **Seedless Wallet**, and **Custom Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. The labels describe setup paths, without a “Featured” badge or a blanket seed-word promise on the card. Single-Key, Custom, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. +- Selecting Seedless immediately starts a compact, simulated progress screen rather than a mandatory introduction: Mobile Key then Server Key status labels advance in order, Hardware Key waits for the user, and **Choose Hardware** enables only after both demo steps. “How it works” is optional in-flow detail; the complete policy remains a required review before any real wallet could be created. The timer changes labels only: it creates no key, backup, server registration, or wallet. A future real “Added” status must wait for verified secure Mobile Key persistence or Server Key registration, respectively; elapsed time cannot establish readiness. - The default Seedless design calls for an independently generated Mobile Key and no new seed words for the user to record. Derivation from Keeper's existing 12-word Recovery Key remains an **optional creation path**, not a setup prerequisite or chooser message. The isolated BIP85 helper reserves a versioned child range starting at index 1,000,000; Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Seedless. Its pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. A Recovery Key cannot recreate a separately generated Mobile Key by derivation alone; that would require a reviewed encrypted backup or wrapping design. - A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. Its 2-of-3 and delayed 2-of-4 results are explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). - A client-only Recovery Contact state model covers encrypted-cloud readback receipts, offline retry, invitation/request expiry, approval/decline, and optional recovery-code gating. It stops before cryptographic enrollment or restoration. No contact key, encrypted backup, native cloud container, or independent exchange channel exists yet. See [recovery-contact.md](recovery-contact.md). - The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. - Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. -The latest client code passed **70 Jest tests across 12 focused suites** covering the direct empty Wallets entry, Add Wallet chooser, preview isolation, Recovery Key education gate, key-origin policy draft, contact states, and Recovery Key migration. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. +The latest client code passed **71 Jest tests across 12 focused suites** covering the direct empty Wallets entry, timed simulated status progression and disabled hardware action, Add Wallet chooser, preview isolation, Recovery Key education gate, key-origin policy draft, contact states, and Recovery Key migration. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. ## Owner decision (8 October 2026) diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index 401e1288d..8cadf8d13 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -1,5 +1,13 @@ import React, { useEffect, useRef, useState } from 'react'; -import { BackHandler, PixelRatio, Pressable, ScrollView, StyleSheet, View } from 'react-native'; +import { + ActivityIndicator, + BackHandler, + PixelRatio, + Pressable, + ScrollView, + StyleSheet, + View, +} from 'react-native'; import { NativeBaseProvider, useColorMode } from '@gluestack-ui/themed-native-base'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context'; @@ -57,6 +65,7 @@ const SAMPLE_REQUEST = { replacementDeviceKeyId: 'sample-no-device-key', expiresAt: SAMPLE_NOW + 600, }; +const SIMULATED_KEY_STEP_MS = 800; function PreviewText({ children, style, color, ...props }: any) { const fontScale = Math.min(PixelRatio.getFontScale(), 2); @@ -189,6 +198,8 @@ function PreviewContent() { const [surface, setSurface] = useState('wallets'); const [choiceOrigin, setChoiceOrigin] = useState<'wallets' | 'chooser'>('wallets'); const [draft, setDraft] = useState(initialPreviewDraft); + const [automaticStep, setAutomaticStep] = useState<0 | 1 | 2>(0); + const [showHowItWorks, setShowHowItWorks] = useState(false); const [contactEnrollment, setContactEnrollment] = useState(initialContactEnrollment); const [contactSample, setContactSample] = useState<'overview' | 'invitation' | 'request'>( @@ -200,6 +211,11 @@ function PreviewContent() { const [requestDecision, setRequestDecision] = useState(null); const scrollRef = useRef(null); const act = (action: PreviewAction) => setDraft((current) => reducePreviewDraft(current, action)); + const resetWalkthrough = () => { + act({ type: 'RESET' }); + setAutomaticStep(0); + setShowHowItWorks(false); + }; const exitFlow = () => setSurface(choiceOrigin); const openChoice = (choice: PreviewSurface) => { setChoiceOrigin(surface === 'chooser' ? 'chooser' : 'wallets'); @@ -245,7 +261,7 @@ function PreviewContent() { else if (surface === 'hot' || surface === 'cold') setSurface('simple'); else if (surface === 'advanced' || surface === 'import') setSurface(choiceOrigin); else if (surface === 'seedless' && draft.stage === 'complete') { - act({ type: 'RESET' }); + resetWalkthrough(); exitFlow(); } else if (surface === 'seedless' && draft.stage === 'automatic') exitFlow(); else if (surface === 'seedless') act({ type: 'BACK' }); @@ -264,9 +280,23 @@ function PreviewContent() { scrollRef.current?.scrollTo({ y: 0, animated: false }); }, [surface, draft.stage]); + useEffect(() => { + if (surface !== 'seedless' || draft.stage !== 'automatic' || automaticStep === 2) + return undefined; + // Demonstration only: these timers change labels, not key or server state. + const timer = setTimeout( + () => setAutomaticStep((current) => (current === 0 ? 1 : 2)), + SIMULATED_KEY_STEP_MS + ); + return () => clearTimeout(timer); + }, [surface, draft.stage, automaticStep]); + const selectedDevice = HARDWARE_CHOICES.find(({ id }) => id === draft.hardware); const hasDraft = - draft.stage !== 'automatic' || draft.hardware !== null || draft.inheritanceEnabled; + automaticStep > 0 || + draft.stage !== 'automatic' || + draft.hardware !== null || + draft.inheritanceEnabled; const walletChooser = (fromWallets: boolean) => ( openChoice('simple')} @@ -309,7 +339,7 @@ function PreviewContent() { ? 'Cloud Backup' : surface === 'contact' ? 'Recovery Contact' - : 'Wallet Preview' + : 'Seedless Wallet' } onBack={surface === 'wallets' ? undefined : back} palette={palette} @@ -425,45 +455,110 @@ function PreviewContent() { {surface === 'seedless' && draft.stage === 'automatic' && ( - Automatic Keys + Setting up your keys - The proposed wallet needs 2 of 3 keys to spend. These statuses demonstrate the - intended automatic setup. No key material has been generated. + The first two steps run automatically. Then choose your hardware. - - In the proposed setup, you would not write down seed words for this wallet. Your - signing device may have its own backup steps. - - - - Mobile Key - - - Ready status · SIMULATED - - - The app would prepare this key automatically. There is no Mobile Key or cloud backup - in this preview. - - - - - Server Key - - - Ready status · SIMULATED - - - No Server Key has been requested or registered. Server Key is one key in your - wallet. Keeper cannot spend your bitcoin with this key alone. - - + + + + {automaticStep === 0 ? ( + + ) : ( + + ✓ + + )} + + + Mobile Key + + + {automaticStep === 0 ? 'Adding… · SIMULATED' : 'Added · SIMULATED'} + + + + + + + {automaticStep === 1 ? ( + + ) : ( + + {automaticStep === 2 ? '✓' : '○'} + + )} + + + Server Key + + + {automaticStep === 0 + ? 'Waiting · SIMULATED' + : automaticStep === 1 + ? 'Adding… · SIMULATED' + : 'Added · SIMULATED'} + + + + + + + + ○ + + + + Hardware Key + + + {automaticStep === 2 ? 'Choose your device' : 'Waiting for you'} + + + + + act({ type: 'NEXT' })} palette={palette} /> + setShowHowItWorks((visible) => !visible)} + palette={palette} + testID="preview-how-it-works" + /> + {showHowItWorks && ( + + + How it works + + + The proposed wallet needs any 2 of 3 keys to spend: Mobile Key, Server Key, and + Hardware Key. Keeper cannot spend with Server Key alone. Your signing device may + have its own backup steps. + + + This preview only changes status labels. No key material has been generated, and + no Server Key has been requested or registered. + + + )} + + Your signing device may have its own backup steps. + @@ -682,7 +780,7 @@ function PreviewContent() { /> act({ type: 'RESET' })} + onPress={resetWalkthrough} palette={palette} testID="preview-start-again" /> @@ -974,6 +1072,9 @@ const styles = StyleSheet.create({ banner: { borderRadius: 10, padding: 14, marginTop: 8 }, bannerText: { fontSize: 14, lineHeight: 21, fontWeight: '500' }, status: { fontSize: 13, lineHeight: 19, fontWeight: '600' }, + progressRow: { flexDirection: 'row', alignItems: 'center', gap: 12 }, + progressCopy: { flex: 1, gap: 3 }, + stepIcon: { width: 22, fontSize: 20, lineHeight: 26, textAlign: 'center' }, linkButton: { alignItems: 'center', justifyContent: 'center', minHeight: 44, padding: 8 }, linkText: { fontSize: 15, fontWeight: '600' }, primaryButton: { diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index cdd77d02c..cb1c85e11 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Dimensions, PixelRatio, StyleSheet } from 'react-native'; import { NativeBaseProvider } from '@gluestack-ui/themed-native-base'; -import { fireEvent, render } from '@testing-library/react-native'; +import { act, fireEvent, render } from '@testing-library/react-native'; import WalletCreationChooser from '../../src/components/WalletCreationChooser'; import { customTheme } from '../../src/navigation/themes'; import RecoverableWalletPreviewApp from '../../src/preview/recoverable-wallet/RecoverableWalletPreviewApp'; @@ -26,9 +26,15 @@ jest.mock('src/components/KeeperText', () => { return ({ children, ...props }) => {children}; }); +function finishSimulatedAutomaticSetup() { + act(() => jest.advanceTimersByTime(800)); + act(() => jest.advanceTimersByTime(800)); +} + function enterRecoveryOptions(screen) { fireEvent.press(screen.getByTestId('wallet-choice-seedless')); - fireEvent.press(screen.getByTestId('primary-Continue')); + finishSimulatedAutomaticSetup(); + fireEvent.press(screen.getByTestId('primary-Choose Hardware')); fireEvent.press(screen.getByTestId('preview-hardware-Coldcard')); fireEvent.press(screen.getByTestId('primary-Continue')); fireEvent.press(screen.getByTestId('preview-continue-simulation')); @@ -39,13 +45,19 @@ function enterRecoveryOptions(screen) { describe('Recoverable Wallet preview on a small screen', () => { beforeEach(() => { + jest.useFakeTimers(); jest .spyOn(Dimensions, 'get') .mockReturnValue({ width: 320, height: 640, scale: 2, fontScale: 1.6 }); jest.spyOn(PixelRatio, 'getFontScale').mockReturnValue(1.6); }); - test('keeps security copy available, reaches one final review, and resumes after cancel', () => { + afterEach(() => { + jest.useRealTimers(); + jest.restoreAllMocks(); + }); + + test('starts automatic status progress on selection, pauses on cancel, and waits for hardware', () => { const screen = render(); expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('No wallets yet'); expect(screen.queryByTestId('primary-Add Wallet')).toBeNull(); @@ -53,19 +65,58 @@ describe('Recoverable Wallet preview on a small screen', () => { expect(screen.getByTestId('preview-simulation-banner')).toHaveTextContent( 'Simulated walkthrough' ); - expect(screen.getByTestId('preview-automatic')).toHaveTextContent( - 'No key material has been generated' + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent( + 'Waiting · SIMULATED' + ); + expect(screen.getByTestId('preview-hardware-key-status')).toHaveTextContent('Waiting for you'); + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + true + ); + fireEvent.press(screen.getByTestId('primary-Choose Hardware')); + expect(screen.queryByTestId('preview-hardware')).toBeNull(); + act(() => jest.advanceTimersByTime(800)); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent('Added · SIMULATED'); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + fireEvent.press(screen.getByTestId('preview-cancel')); + act(() => jest.advanceTimersByTime(1600)); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + act(() => jest.advanceTimersByTime(800)); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent('Added · SIMULATED'); + expect(screen.getByTestId('preview-hardware-key-status')).toHaveTextContent( + 'Choose your device' ); - expect(screen.getByTestId('preview-automatic')).toHaveTextContent( + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + false + ); + expect(screen.queryByTestId('preview-hardware')).toBeNull(); + fireEvent.press(screen.getByTestId('preview-how-it-works')); + expect(screen.getByTestId('preview-how-it-works-details')).toHaveTextContent( 'Your signing device may have its own backup steps.' ); - const serverWarning = screen.getByText(/Keeper cannot spend your bitcoin with this key alone/); + const serverWarning = screen.getByText(/Keeper cannot spend with Server Key alone/); expect(serverWarning.props.allowFontScaling).toBe(true); expect(StyleSheet.flatten(serverWarning.props.style).lineHeight).toBeGreaterThan(23); - const primaryLabel = screen.getByText('Continue'); + const primaryLabel = screen.getByText('Choose Hardware'); expect(primaryLabel.props.allowFontScaling).toBe(true); expect(primaryLabel.props.numberOfLines).toBeUndefined(); - fireEvent.press(screen.getByTestId('primary-Continue')); + expect(screen.getByTestId('preview-how-it-works-details')).toHaveTextContent( + 'No key material has been generated' + ); + }); + + test('reaches one final review, and resumes hardware after cancel', () => { + const screen = render(); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + finishSimulatedAutomaticSetup(); + fireEvent.press(screen.getByTestId('primary-Choose Hardware')); expect(screen.getByTestId('primary-Continue').props.accessibilityState.disabled).toBe(true); fireEvent.press(screen.getByTestId('preview-hardware-Coldcard')); fireEvent.press(screen.getByTestId('primary-Continue')); @@ -83,6 +134,9 @@ describe('Recoverable Wallet preview on a small screen', () => { fireEvent.press(screen.getByTestId('preview-inheritance-toggle')); fireEvent.press(screen.getByTestId('primary-Review Policy')); expect(screen.getByTestId('preview-review')).toHaveTextContent('Spending now · 2 of 3'); + expect(screen.getByTestId('preview-review')).toHaveTextContent( + 'Your signing device may have its own backup steps.' + ); expect(screen.getByTestId('preview-review')).toHaveTextContent( 'designated second signer available without Server Key' ); @@ -91,6 +145,10 @@ describe('Recoverable Wallet preview on a small screen', () => { expect(screen.getByTestId('preview-complete')).toHaveTextContent('No wallet was created'); fireEvent.press(screen.getByTestId('preview-done')); expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('Seedless Wallet'); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); }); test('navigates the three-choice entry and keeps other paths simulated', () => { From 3b5e84d5b91a2471dfe3a74e422d572479630393 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 16:09:11 +0530 Subject: [PATCH 09/31] Gate inheritance preview by hardware policy capability --- docs/preview/recoverable-wallet/README.md | 4 +- .../recoverable-wallet/native-preview.md | 2 +- .../RecoverableWalletPreviewApp.tsx | 76 +++++++++++++------ src/preview/recoverable-wallet/previewFlow.ts | 34 +++++++-- .../preview/recoverableWalletPreview.test.ts | 43 ++++++++++- .../preview/recoverableWalletScreen.test.tsx | 47 ++++++++++++ 6 files changed, 168 insertions(+), 38 deletions(-) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index b74d4c11d..d5e7cd301 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -5,7 +5,7 @@ Status (9 October 2026): **isolated client preview and direct three-choice empty ## First client checkpoint - The packaged first preview starts at **Add Wallet** and walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. -- TAPSIGNER, Satochip, Jade, and Coldcard appear with their existing Keeper transport choices. The UI says policy verification and full Recoverable Wallet compatibility remain unproven. Every simulated status, error, and completion is labeled. +- TAPSIGNER, Satochip, Jade, and Coldcard appear with their existing Keeper transport choices. The UI says policy verification and full Recoverable Wallet compatibility remain unproven. Every simulated status, error, and completion is labeled. The latest source offers only the base 2-of-3 proposal for TAPSIGNER, Satochip, and Jade; Coldcard alone can proceed to an explicitly unverified Inheritance Key proposal. - The app entry requires the exact preview package ID and testnet-only preview flags. Normal Keeper continues through its original app component. The preview loads no wallet store, cloud backup, signing, or server client. The native preview identifiers are distinct, the Android CloudBackup module is disabled, and the iOS preview has no iCloud entitlement. See [native-preview.md](native-preview.md). - An arm64 Android debug APK with an embedded JavaScript bundle was built and its package identity, signature, and merged manifest were checked. It installed and ran beside an existing Keeper development app on an Android emulator. Side-by-side installation with production Keeper on a physical device remains unverified. The iOS preview scheme, identifier, plist, and entitlements are configured, but an iOS build has not been run: this checkout lacks matching Pods and has insufficient free disk space for a safe fresh install/build. @@ -30,7 +30,7 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr - The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. - Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. -The latest client code passed **71 Jest tests across 12 focused suites** covering the direct empty Wallets entry, timed simulated status progression and disabled hardware action, Add Wallet chooser, preview isolation, Recovery Key education gate, key-origin policy draft, contact states, and Recovery Key migration. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. +The latest client code passed **79 Jest tests across 12 focused suites** covering the direct empty Wallets entry, timed simulated status progression and disabled hardware action, Add Wallet chooser, preview isolation, hardware-dependent inheritance gating, Recovery Key education gate, key-origin policy draft, contact states, and Recovery Key migration. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. ## Owner decision (8 October 2026) diff --git a/docs/preview/recoverable-wallet/native-preview.md b/docs/preview/recoverable-wallet/native-preview.md index 777aecb75..30c96c202 100644 --- a/docs/preview/recoverable-wallet/native-preview.md +++ b/docs/preview/recoverable-wallet/native-preview.md @@ -38,7 +38,7 @@ Before future cloud backup work, register a dedicated iCloud container for the p ## Native checks 1. Confirm production Keeper and Keeper Preview install simultaneously without replacing each other. -2. Confirm the preview icon/name is `Keeper Preview`, has no production deep link/backup intent, and starts directly in the simulated flow. +2. Confirm the preview icon/name is `Keeper Preview`, has no production deep link/backup intent, and starts at the empty Wallets chooser. Selecting Seedless Wallet should start the simulated key sequence directly. 3. Check iOS Keychain and Android app data remain inaccessible to the other app. On iOS, inspect the signed preview entitlements; they must contain no production iCloud or Keychain group. 4. Confirm both preview backends use only local unreachable URLs and the UI has no mainnet control, wallet creation, signing, or cloud-backup action. 5. Uninstall Preview and confirm production Keeper and its wallet/backups remain intact. diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index 8cadf8d13..7ebff44ee 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -26,6 +26,7 @@ import { } from 'src/services/wallets/recoverable/contactRecoveryFlow'; import { HARDWARE_CHOICES, + canPreviewInheritanceForHardware, initialPreviewDraft, PreviewAction, PreviewDraft, @@ -292,6 +293,7 @@ function PreviewContent() { }, [surface, draft.stage, automaticStep]); const selectedDevice = HARDWARE_CHOICES.find(({ id }) => id === draft.hardware); + const canProposeInheritance = canPreviewInheritanceForHardware(draft.hardware); const hasDraft = automaticStep > 0 || draft.stage !== 'automatic' || @@ -665,31 +667,47 @@ function PreviewContent() { Inheritance Key - - Proposal, not configured: an Inheritance Key would give your heir a delayed path after - a fixed on-chain unlock date. Opening Keeper would not reset that date. - - act({ type: 'SET_INHERITANCE', enabled: !draft.inheritanceEnabled })} - > - - - {draft.inheritanceEnabled ? '✓ Add Inheritance Key' : '○ Add Inheritance Key'} - + {canProposeInheritance ? ( + <> - Optional. It does not lower the 2-of-3 spending requirement today. + Proposal, not configured: an Inheritance Key would give your heir a delayed path + after a fixed on-chain unlock date. Opening Keeper would not reset that date. - - - {draft.inheritanceEnabled && ( - - SIMULATED PROPOSAL · Your heir would need an Inheritance Key and a second signer - they can access without Server Key. Changing the unlock date would require a new - wallet and moving bitcoin. No heir, date, signer, or Miniscript policy is - configured. + + UNVERIFIED CANDIDATE · Coldcard has not been proven to register or sign this full + inheritance policy. No Inheritance Key or policy is created here. + + + act({ type: 'SET_INHERITANCE', enabled: !draft.inheritanceEnabled }) + } + > + + + {draft.inheritanceEnabled ? '✓ Add Inheritance Key' : '○ Add Inheritance Key'} + + + Optional. It does not lower the 2-of-3 spending requirement today. + + + + {draft.inheritanceEnabled && ( + + SIMULATED PROPOSAL · Your heir would need an Inheritance Key and a second signer + they can access without Server Key. Changing the unlock date would require a new + wallet and moving bitcoin. No heir, date, signer, or Miniscript policy is + configured. + + )} + + ) : ( + + Inheritance Key is unavailable with {selectedDevice?.id} in this preview. Keeper + cannot verify the full delayed policy with this device yet. Continue with 2 of 3 or + change device. )} act({ type: 'NEXT' })} palette={palette} /> + act({ type: 'CHANGE_HARDWARE' })} + palette={palette} + testID="preview-change-hardware" + /> {draft.inheritanceEnabled - ? 'Proposed delayed path, not configured: after a fixed on-chain unlock date, your heir would use an Inheritance Key plus a designated second signer available without Server Key. Opening Keeper would not reset the date. Changing it would require a new wallet and moving bitcoin. No date, signer, or Miniscript policy exists in this preview.' - : 'The proposed wallet has only the base 2-of-3 spending path.'} + ? 'Proposed delayed path, not configured: after a fixed on-chain unlock date, your heir would use an Inheritance Key plus a designated second signer available without Server Key. Opening Keeper would not reset the date. Changing it would require a new wallet and moving bitcoin. No date, signer, or Miniscript policy exists in this preview. Coldcard compatibility remains unverified.' + : canProposeInheritance + ? 'The proposed wallet has only the base 2-of-3 spending path.' + : `The proposed wallet has only the base 2-of-3 spending path. Inheritance Key is unavailable with ${selectedDevice?.id} in this preview.`} diff --git a/src/preview/recoverable-wallet/previewFlow.ts b/src/preview/recoverable-wallet/previewFlow.ts index da6f84ebd..fb6bebf40 100644 --- a/src/preview/recoverable-wallet/previewFlow.ts +++ b/src/preview/recoverable-wallet/previewFlow.ts @@ -2,26 +2,29 @@ export const HARDWARE_CHOICES = [ { id: 'TAPSIGNER', transport: 'NFC', - verification: 'Signing device; full wallet policy cannot be verified on the card.', + verification: 'Inheritance Key unavailable; the card cannot verify the full delayed policy.', }, { id: 'Satochip', transport: 'NFC', - verification: 'Signing device; full wallet policy cannot be verified on the card.', + verification: 'Inheritance Key unavailable; the card cannot verify the full delayed policy.', }, { id: 'Jade', transport: 'QR or Keeper Desktop USB', - verification: 'Full Recoverable Wallet policy compatibility is not yet verified.', + verification: 'Inheritance Key unavailable; full policy verification is not yet supported.', }, { id: 'Coldcard', transport: 'QR, file, NFC, or Keeper Desktop USB', - verification: 'Full Recoverable Wallet policy compatibility is not yet verified.', + verification: 'Inheritance Key review candidate; full policy support remains unverified.', }, ] as const; export type PreviewHardware = (typeof HARDWARE_CHOICES)[number]['id']; +/** Matches the public policy draft's current inheritance capability gate. */ +export const canPreviewInheritanceForHardware = (hardware: PreviewHardware | null): boolean => + hardware === 'Coldcard'; export type PreviewStage = | 'automatic' | 'hardware' @@ -51,6 +54,7 @@ export type PreviewAction = | { type: 'ATTEMPT_CONNECTION' } | { type: 'CONTINUE_SIMULATION' } | { type: 'SET_INHERITANCE'; enabled: boolean } + | { type: 'CHANGE_HARDWARE' } | { type: 'RESET' }; export function reducePreviewDraft(draft: PreviewDraft, action: PreviewAction): PreviewDraft { @@ -59,7 +63,7 @@ export function reducePreviewDraft(draft: PreviewDraft, action: PreviewAction): return initialPreviewDraft; case 'SELECT_HARDWARE': return draft.stage === 'hardware' && HARDWARE_CHOICES.some(({ id }) => id === action.hardware) - ? { ...draft, hardware: action.hardware, connectionAttempts: 0 } + ? { ...draft, hardware: action.hardware, connectionAttempts: 0, inheritanceEnabled: false } : draft; case 'ATTEMPT_CONNECTION': return draft.stage === 'connect' @@ -70,13 +74,29 @@ export function reducePreviewDraft(draft: PreviewDraft, action: PreviewAction): ? { ...draft, stage: 'inheritance' } : draft; case 'SET_INHERITANCE': - return draft.stage === 'inheritance' + return draft.stage === 'inheritance' && + (!action.enabled || canPreviewInheritanceForHardware(draft.hardware)) ? { ...draft, inheritanceEnabled: action.enabled } : draft; + case 'CHANGE_HARDWARE': + return draft.stage === 'inheritance' + ? { + ...draft, + stage: 'hardware', + hardware: null, + connectionAttempts: 0, + inheritanceEnabled: false, + } + : draft; case 'NEXT': if (draft.stage === 'automatic') return { ...draft, stage: 'hardware' }; if (draft.stage === 'hardware' && draft.hardware) return { ...draft, stage: 'connect' }; - if (draft.stage === 'inheritance' && draft.hardware) return { ...draft, stage: 'review' }; + if ( + draft.stage === 'inheritance' && + draft.hardware && + (!draft.inheritanceEnabled || canPreviewInheritanceForHardware(draft.hardware)) + ) + return { ...draft, stage: 'review' }; if (draft.stage === 'review' && draft.hardware) return { ...draft, stage: 'complete' }; return draft; case 'BACK': diff --git a/tests/preview/recoverableWalletPreview.test.ts b/tests/preview/recoverableWalletPreview.test.ts index b41198f7d..bd1df99e0 100644 --- a/tests/preview/recoverableWalletPreview.test.ts +++ b/tests/preview/recoverableWalletPreview.test.ts @@ -49,16 +49,16 @@ describe('Recoverable Wallet walkthrough', () => { expect(reducePreviewDraft(reviewStage, { type: 'NEXT' }).stage).toBe('complete'); }); - test('inheritance is chosen before one final review and remains editable when going back', () => { + test('Coldcard inheritance remains an unverified proposal before one final review', () => { let draft = reducePreviewDraft(initialPreviewDraft, { type: 'NEXT' }); - draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware: 'Satochip' }); + draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware: 'Coldcard' }); draft = reducePreviewDraft(draft, { type: 'NEXT' }); draft = reducePreviewDraft(draft, { type: 'CONTINUE_SIMULATION' }); draft = reducePreviewDraft(draft, { type: 'SET_INHERITANCE', enabled: true }); draft = reducePreviewDraft(draft, { type: 'NEXT' }); expect(draft).toMatchObject({ stage: 'review', - hardware: 'Satochip', + hardware: 'Coldcard', inheritanceEnabled: true, }); @@ -68,6 +68,43 @@ describe('Recoverable Wallet walkthrough', () => { expect(draft).toMatchObject({ stage: 'review', inheritanceEnabled: false }); }); + test.each(['TAPSIGNER', 'Satochip', 'Jade'] as const)( + '%s cannot enter the inheritance proposal but can review base 2-of-3', + (hardware) => { + let draft = reducePreviewDraft(initialPreviewDraft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware }); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'CONTINUE_SIMULATION' }); + expect(reducePreviewDraft(draft, { type: 'SET_INHERITANCE', enabled: true })).toEqual(draft); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + expect(draft).toMatchObject({ stage: 'review', hardware, inheritanceEnabled: false }); + expect( + reducePreviewDraft( + { ...draft, stage: 'inheritance', inheritanceEnabled: true }, + { type: 'NEXT' } + ).stage + ).toBe('inheritance'); + } + ); + + test('changing away from Coldcard discards the old inheritance choice', () => { + let draft = reducePreviewDraft(initialPreviewDraft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware: 'Coldcard' }); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'CONTINUE_SIMULATION' }); + draft = reducePreviewDraft(draft, { type: 'SET_INHERITANCE', enabled: true }); + draft = reducePreviewDraft(draft, { type: 'CHANGE_HARDWARE' }); + expect(draft).toMatchObject({ + stage: 'hardware', + hardware: null, + inheritanceEnabled: false, + }); + draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware: 'Jade' }); + draft = reducePreviewDraft(draft, { type: 'NEXT' }); + draft = reducePreviewDraft(draft, { type: 'CONTINUE_SIMULATION' }); + expect(reducePreviewDraft(draft, { type: 'SET_INHERITANCE', enabled: true })).toEqual(draft); + }); + test('a connection attempt never marks hardware connected and a reset discards the draft', () => { let draft = reducePreviewDraft(initialPreviewDraft, { type: 'NEXT' }); draft = reducePreviewDraft(draft, { type: 'SELECT_HARDWARE', hardware: 'TAPSIGNER' }); diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index cb1c85e11..e319ba67c 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -131,6 +131,9 @@ describe('Recoverable Wallet preview on a small screen', () => { fireEvent.press(screen.getByTestId('wallet-choice-seedless')); expect(screen.getByTestId('preview-connect')).toHaveTextContent('Coldcard'); fireEvent.press(screen.getByTestId('preview-continue-simulation')); + expect(screen.getByTestId('preview-inheritance-candidate')).toHaveTextContent( + 'Coldcard has not been proven to register or sign' + ); fireEvent.press(screen.getByTestId('preview-inheritance-toggle')); fireEvent.press(screen.getByTestId('primary-Review Policy')); expect(screen.getByTestId('preview-review')).toHaveTextContent('Spending now · 2 of 3'); @@ -151,6 +154,50 @@ describe('Recoverable Wallet preview on a small screen', () => { ); }); + test.each(['TAPSIGNER', 'Satochip', 'Jade'] as const)( + 'shows %s inheritance unavailable and retains the base 2-of-3 path', + (hardware) => { + const screen = render(); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + finishSimulatedAutomaticSetup(); + fireEvent.press(screen.getByTestId('primary-Choose Hardware')); + fireEvent.press(screen.getByTestId(`preview-hardware-${hardware}`)); + fireEvent.press(screen.getByTestId('primary-Continue')); + fireEvent.press(screen.getByTestId('preview-continue-simulation')); + expect(screen.getByTestId('preview-inheritance-unavailable')).toHaveTextContent( + `Inheritance Key is unavailable with ${hardware}` + ); + expect(screen.queryByTestId('preview-inheritance-toggle')).toBeNull(); + fireEvent.press(screen.getByTestId('primary-Review Policy')); + expect(screen.getByTestId('preview-review')).toHaveTextContent( + `Inheritance Key is unavailable with ${hardware}` + ); + expect(screen.getByTestId('preview-review')).toHaveTextContent( + 'only the base 2-of-3 spending path' + ); + } + ); + + test('can change device from blocked inheritance to an unverified Coldcard proposal', () => { + const screen = render(); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + finishSimulatedAutomaticSetup(); + fireEvent.press(screen.getByTestId('primary-Choose Hardware')); + fireEvent.press(screen.getByTestId('preview-hardware-Jade')); + fireEvent.press(screen.getByTestId('primary-Continue')); + fireEvent.press(screen.getByTestId('preview-continue-simulation')); + fireEvent.press(screen.getByTestId('preview-change-hardware')); + expect(screen.getByTestId('preview-hardware')).toBeTruthy(); + expect(screen.getByTestId('primary-Continue').props.accessibilityState.disabled).toBe(true); + fireEvent.press(screen.getByTestId('preview-hardware-Coldcard')); + fireEvent.press(screen.getByTestId('primary-Continue')); + fireEvent.press(screen.getByTestId('preview-continue-simulation')); + expect(screen.getByTestId('preview-inheritance-candidate')).toBeTruthy(); + expect(screen.getByTestId('preview-inheritance-toggle').props.accessibilityState.checked).toBe( + false + ); + }); + test('navigates the three-choice entry and keeps other paths simulated', () => { const screen = render(); const chooser = screen.getByTestId('wallet-creation-chooser'); From 72c57ab9e897a46f179e3954d5ea757b6c448673 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 16:50:32 +0530 Subject: [PATCH 10/31] Advance simulated Seedless setup and preview Mobile Key groundwork --- docs/preview/recoverable-wallet/README.md | 16 +- .../recoverable-wallet/native-preview.md | 2 +- .../RecoverableWalletPreviewApp.tsx | 124 +++++-- .../recoverable-wallet/simulatedSetup.ts | 39 +++ .../wallets/recoverable/deviceMobileKey.ts | 311 ++++++++++++++++++ .../preview/recoverableWalletPreview.test.ts | 24 ++ .../preview/recoverableWalletScreen.test.tsx | 82 ++++- .../recoverable/deviceMobileKey.test.ts | 272 +++++++++++++++ 8 files changed, 833 insertions(+), 37 deletions(-) create mode 100644 src/preview/recoverable-wallet/simulatedSetup.ts create mode 100644 src/services/wallets/recoverable/deviceMobileKey.ts create mode 100644 tests/services/recoverable/deviceMobileKey.test.ts diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index d5e7cd301..e5e54ce49 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -1,22 +1,22 @@ # Recoverable Wallet — parallel Keeper preview -Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; Android package built for the earlier checkpoint; iOS package configured but not built**. The revised empty-state chooser has not yet been packaged in a new APK. This is a simulated walkthrough, not a released or security-reviewed wallet. "Seedless Wallet" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. +Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Seedless Wallet" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. ## First client checkpoint -- The packaged first preview starts at **Add Wallet** and walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. +- The current package starts at the empty **Wallets** screen with Single-Key, Seedless, and Custom choices; Add Wallet opens the same chooser. Seedless walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. - TAPSIGNER, Satochip, Jade, and Coldcard appear with their existing Keeper transport choices. The UI says policy verification and full Recoverable Wallet compatibility remain unproven. Every simulated status, error, and completion is labeled. The latest source offers only the base 2-of-3 proposal for TAPSIGNER, Satochip, and Jade; Coldcard alone can proceed to an explicitly unverified Inheritance Key proposal. - The app entry requires the exact preview package ID and testnet-only preview flags. Normal Keeper continues through its original app component. The preview loads no wallet store, cloud backup, signing, or server client. The native preview identifiers are distinct, the Android CloudBackup module is disabled, and the iOS preview has no iCloud entitlement. See [native-preview.md](native-preview.md). -- An arm64 Android debug APK with an embedded JavaScript bundle was built and its package identity, signature, and merged manifest were checked. It installed and ran beside an existing Keeper development app on an Android emulator. Side-by-side installation with production Keeper on a physical device remains unverified. The iOS preview scheme, identifier, plist, and entitlements are configured, but an iOS build has not been run: this checkout lacks matching Pods and has insufficient free disk space for a safe fresh install/build. +- An arm64 Android debug APK with an embedded JavaScript bundle was built and its package identity and debug signature checked. It installed and ran beside both a Keeper development app and the public production Keeper v2.6.3 APK on an Android emulator. Side-by-side installation and storage isolation on physical devices remain unverified. The iOS preview scheme, identifier, plist, and entitlements are configured, but an iOS build has not been run: this checkout lacks matching Pods and has insufficient free disk space for a safe fresh install/build. | Evidence | Current result | | --- | --- | | Simulated client flow | Automated walkthrough covers four hardware choices, cancel/resume, connection error, inheritance choice, and final review. | -| Startup boundary and related regressions | 27 focused Jest tests pass across the preview, testnet header, and Recovery Key migration suites. | +| Startup boundary and related regressions | 98 focused Jest tests pass across 13 preview and related service suites. | | Native build | Android arm64 debug APK built with embedded JS, installed and launched on an arm64 emulator; iOS scheme configuration inspected, build pending. | | Small-screen rendering | Android emulator walkthrough passed at 320dp width and 1.6× system font: statuses, four hardware choices, simulated error, inheritance, review, and completion remained scrollable and actionable. The Jest content check alone does not establish rendered layout. | -| Physical devices and production side-by-side installation | Pending. The emulator had Keeper development installed, not production Keeper. | -| Cryptography, cloud read-back, physical hardware, security review | Pending; no such functions are represented as complete in this preview. | +| Physical devices and production side-by-side installation | Production v2.6.3 and Preview co-installed and launched on the emulator. Physical installation and cross-app storage isolation are pending. | +| Cryptography, cloud read-back, physical hardware, security review | Pending. A device-generated Mobile Key service is unit tested but remains unwired and is not a wallet-ready state. | The next owner test is to install the Android APK beside normal Keeper, walk through both inheritance choices and a simulated error, verify text and controls at a small screen width with larger system font, then uninstall Preview and confirm the normal app and backups remain intact. Equivalent iOS testing follows a fresh matching Pods install, simulator/device build, and preview App ID/provisioning setup. Do not use real wallet funds or production recovery material in either preview. @@ -30,7 +30,9 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr - The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. - Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. -The latest client code passed **79 Jest tests across 12 focused suites** covering the direct empty Wallets entry, timed simulated status progression and disabled hardware action, Add Wallet chooser, preview isolation, hardware-dependent inheritance gating, Recovery Key education gate, key-origin policy draft, contact states, and Recovery Key migration. The chooser and recovery tests render at a mocked 320px width and 1.6× text scale, but that is not a native layout check. A fresh arm64 Android build was attempted on 9 October and stopped during bundling when free disk fell from 4.3 GiB to 1.0 GiB; no new APK or native screenshot was produced. The temporary Metro adjustment was reverted. The Android APK and emulator results in the first checkpoint above describe the **earlier package**, before this chooser. Do not distribute that package as a test of the new three-choice screen. +The latest client code passed **98 Jest tests across 13 focused suites** covering the direct empty Wallets entry, simulated Mobile/Server failure and retry, Add Wallet chooser, preview isolation, hardware-dependent inheritance gating, Recovery Key education gate, device Mobile Key derivation and storage error handling, key-origin policy draft, contact states, and Recovery Key migration. The latest arm64 APK embeds this chooser, shorter copy, and simulated setup error/retry states. An Android emulator walkthrough at 320dp and 1.6× system font confirmed that the three-choice landing, Mobile/Server statuses, hardware action, persistent setup error sample, and retry remain reachable by scrolling. The complete hardware, inheritance, and final-review walkthrough at that size was recorded against the preceding package; those flow stages did not change in this package. The temporary local Metro symlink adjustment was removed after packaging. + +The separate `deviceMobileKey.ts` service is **not called by the preview UI or wallet creation**. It prepares a testnet BIP48 public Mobile signer from native random bytes and a preview-scoped Keychain record, with a read-back check. This is preparation for a real flow, not proof of a safe fundable key: the installed Keychain library does not provide atomic create-if-absent across runtimes, and the current JavaScript identity check needs a native preview-flavor guard before key creation is connected to real wallet readiness. Native Keychain behavior, backup, restoration, and device isolation remain unverified. ## Owner decision (8 October 2026) diff --git a/docs/preview/recoverable-wallet/native-preview.md b/docs/preview/recoverable-wallet/native-preview.md index 30c96c202..13e92024d 100644 --- a/docs/preview/recoverable-wallet/native-preview.md +++ b/docs/preview/recoverable-wallet/native-preview.md @@ -31,7 +31,7 @@ The local verification worktree shared `node_modules` through a symlink. Metro r The Android package must be installed alongside production Keeper and verified on a device before calling the milestone device-tested. The iOS scheme is configured for the simulator, but a simulator build has not yet completed. A signed physical-device build requires an Apple App ID and provisioning profile for `io.hexawallet.hexakeeper.recoverablepreview`; distribution access must be checked with the Keeper team. Neither cloud backup nor a physical hardware connection is claimed by this milestone. -Local Android emulator verification on 8 October 2026: the arm64 APK installed, launched from its embedded JavaScript bundle, and completed the simulated walkthrough at 320dp width with 1.6× system text. The emulator already had `io.hexawallet.keeper.development` installed; both package IDs remained distinct. The error, inheritance, review, and completion controls were reachable by scrolling. Physical-device installation, production Keeper co-installation, and real storage/keychain separation still require device checks. +Local Android emulator verification on 9 October 2026: the current arm64 APK installed and launched from its embedded JavaScript bundle at 320dp width with 1.6× system text. The shorter testnet demo notice leaves the Seedless option visible on the empty Wallets screen; Mobile and Server simulated statuses and Choose Hardware remain reachable by scrolling. The persistent Show Setup Error action, simulated Server Key failure, and Try Again recovery were exercised in the native app. Keeper Preview, an existing development app, and the public production Keeper v2.6.3 APK had distinct package IDs and launched on the same emulator. The preceding package also completed the simulated hardware, connection error, inheritance, review, and completion walkthrough at that size. Physical-device installation and real storage/keychain separation still require checks. Before future cloud backup work, register a dedicated iCloud container for the preview App ID and dedicated Google OAuth/Drive credentials. Keep access disabled until read-back and cross-app isolation are verified on real devices. Do not reuse Keeper's production or development cloud identities. diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index 7ebff44ee..e7a425615 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -32,6 +32,11 @@ import { PreviewDraft, reducePreviewDraft, } from './previewFlow'; +import { + initialSimulatedSetupState, + reduceSimulatedSetup, + SimulatedSetupState, +} from './simulatedSetup'; type Palette = { background: string; @@ -199,7 +204,9 @@ function PreviewContent() { const [surface, setSurface] = useState('wallets'); const [choiceOrigin, setChoiceOrigin] = useState<'wallets' | 'chooser'>('wallets'); const [draft, setDraft] = useState(initialPreviewDraft); - const [automaticStep, setAutomaticStep] = useState<0 | 1 | 2>(0); + const [automaticSetup, setAutomaticSetup] = useState( + initialSimulatedSetupState + ); const [showHowItWorks, setShowHowItWorks] = useState(false); const [contactEnrollment, setContactEnrollment] = useState(initialContactEnrollment); @@ -214,7 +221,7 @@ function PreviewContent() { const act = (action: PreviewAction) => setDraft((current) => reducePreviewDraft(current, action)); const resetWalkthrough = () => { act({ type: 'RESET' }); - setAutomaticStep(0); + setAutomaticSetup(initialSimulatedSetupState); setShowHowItWorks(false); }; const exitFlow = () => setSurface(choiceOrigin); @@ -282,20 +289,25 @@ function PreviewContent() { }, [surface, draft.stage]); useEffect(() => { - if (surface !== 'seedless' || draft.stage !== 'automatic' || automaticStep === 2) + if ( + surface !== 'seedless' || + draft.stage !== 'automatic' || + (automaticSetup !== 'adding-mobile' && automaticSetup !== 'adding-server') + ) return undefined; // Demonstration only: these timers change labels, not key or server state. const timer = setTimeout( - () => setAutomaticStep((current) => (current === 0 ? 1 : 2)), + () => setAutomaticSetup((current) => reduceSimulatedSetup(current, 'COMPLETE_STEP')), SIMULATED_KEY_STEP_MS ); return () => clearTimeout(timer); - }, [surface, draft.stage, automaticStep]); + }, [surface, draft.stage, automaticSetup]); + const setupFailed = automaticSetup === 'mobile-failed' || automaticSetup === 'server-failed'; const selectedDevice = HARDWARE_CHOICES.find(({ id }) => id === draft.hardware); const canProposeInheritance = canPreviewInheritanceForHardware(draft.hardware); const hasDraft = - automaticStep > 0 || + automaticSetup !== initialSimulatedSetupState || draft.stage !== 'automatic' || draft.hardware !== null || draft.inheritanceEnabled; @@ -356,7 +368,9 @@ function PreviewContent() { {surface !== 'chooser' && ( {surface === 'wallets' - ? 'TESTNET PREVIEW · Simulated choices. No wallet or key is created.' + ? 'TESTNET DEMO · No wallet or key.' + : surface === 'seedless' + ? 'TESTNET DEMO · No wallet or key.' : 'TESTNET PREVIEW · Simulated walkthrough. No wallet, key, address, cloud backup, or server registration is created.'} )} @@ -460,44 +474,64 @@ function PreviewContent() { Setting up your keys - The first two steps run automatically. Then choose your hardware. + Mobile and Server first. Choose hardware next. - {automaticStep === 0 ? ( + {automaticSetup === 'adding-mobile' ? ( ) : ( - - ✓ + + {automaticSetup === 'mobile-failed' ? '!' : '✓'} )} Mobile Key - - {automaticStep === 0 ? 'Adding… · SIMULATED' : 'Added · SIMULATED'} + + {automaticSetup === 'adding-mobile' + ? 'Adding… · SIMULATED' + : automaticSetup === 'mobile-failed' + ? 'Failed · SIMULATED' + : 'Added · SIMULATED'} - {automaticStep === 1 ? ( + {automaticSetup === 'adding-server' ? ( ) : ( - {automaticStep === 2 ? '✓' : '○'} + {automaticSetup === 'server-failed' + ? '!' + : automaticSetup === 'ready' + ? '✓' + : '○'} )} @@ -505,14 +539,22 @@ function PreviewContent() { Server Key - {automaticStep === 0 - ? 'Waiting · SIMULATED' - : automaticStep === 1 + {automaticSetup === 'adding-server' ? 'Adding… · SIMULATED' - : 'Added · SIMULATED'} + : automaticSetup === 'server-failed' + ? 'Failed · SIMULATED' + : automaticSetup === 'ready' + ? 'Added · SIMULATED' + : 'Waiting · SIMULATED'} @@ -527,18 +569,49 @@ function PreviewContent() { Hardware Key - {automaticStep === 2 ? 'Choose your device' : 'Waiting for you'} + {automaticSetup === 'ready' ? 'Choose your device' : 'Waiting for you'} + {setupFailed && ( + + SIMULATED FAILURE ·{' '} + {automaticSetup === 'mobile-failed' ? 'Mobile Key' : 'Server Key'} setup stopped in + this walkthrough. No key or server registration was attempted. + + )} act({ type: 'NEXT' })} + disabled={automaticSetup !== 'ready'} + onPress={() => automaticSetup === 'ready' && act({ type: 'NEXT' })} palette={palette} /> + {setupFailed ? ( + + setAutomaticSetup((current) => reduceSimulatedSetup(current, 'RETRY')) + } + palette={palette} + testID="preview-automatic-retry" + /> + ) : ( + + setAutomaticSetup((current) => + reduceSimulatedSetup( + current, + current === 'ready' ? 'SHOW_SERVER_FAILURE' : 'SIMULATE_FAILURE' + ) + ) + } + palette={palette} + testID="preview-automatic-simulate-failure" + /> + )} setShowHowItWorks((visible) => !visible)} @@ -576,8 +649,7 @@ function PreviewContent() { Choose Hardware - Choose the last base key. Selecting a device here does not connect it or prove that it - can sign the final policy. + Choose a device for the last key. Connection and policy support are not verified here. {HARDWARE_CHOICES.map((choice) => ( ; + setGenericPassword( + username: string, + password: string, + options: { + service: string; + accessible: typeof IOS_ACCESSIBLE; + cloudSync: false; + securityLevel?: typeof ANDROID_SECURITY_LEVEL; + storage?: typeof ANDROID_STORAGE; + } + ): Promise; + }; +} + +interface StoredDeviceMobileKey { + version: typeof RECORD_VERSION; + network: 'testnet'; + signerPath: typeof RECOVERABLE_MOBILE_KEY_SIGNER_PATH; + seedHex: string; + masterFingerprint: string; + xpub: string; +} + +export class DeviceMobileKeyError extends Error { + constructor(public readonly code: string, message: string) { + super(message); + this.name = 'DeviceMobileKeyError'; + } +} + +/** Pure public derivation. The caller retains the seed; this function never returns it. */ +export function deriveDeviceMobileKeyPublic(seed: Uint8Array): RecoverableMobileSigner { + if (!(seed instanceof Uint8Array) || seed.length !== 32) { + throw new DeviceMobileKeyError('INVALID_SEED', 'Mobile Key seed must be 32 bytes'); + } + const root = bip32.fromSeed(Buffer.from(seed), bitcoin.networks.testnet); + const xpub = root.derivePath(RECOVERABLE_MOBILE_KEY_SIGNER_PATH).neutered().toBase58(); + return { + role: 'mobile', + signerType: SignerType.MOBILE_KEY, + masterFingerprint: Buffer.from(root.fingerprint).toString('hex').toUpperCase(), + xpub, + derivationPath: RECOVERABLE_MOBILE_KEY_SIGNER_PATH, + origin: { + kind: 'device-generated', + version: RECORD_VERSION, + // The tpub is public and already returned. It is a stable, unique source reference. + sourceId: `device-generated:${xpub}`, + }, + }; +} + +function decodeNativeEntropy(base64: string): Buffer { + if (typeof base64 !== 'string') { + throw new DeviceMobileKeyError( + 'ENTROPY_UNAVAILABLE', + 'Native secure random bytes are unavailable' + ); + } + const seed = Buffer.from(base64, 'base64'); + if (seed.length !== 32 || seed.toString('base64') !== base64) { + seed.fill(0); + throw new DeviceMobileKeyError('INVALID_ENTROPY', 'Native secure random bytes were invalid'); + } + return seed; +} + +function parseStoredKey( + credentials: StoredCredentials, + service: string, + platform: DeviceMobileKeyAdapters['platform'] +): RecoverableMobileSigner { + if (credentials.service !== service || credentials.username !== KEYCHAIN_USERNAME) { + throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key identity is invalid'); + } + if (platform === 'android' && credentials.storage !== ANDROID_STORAGE) { + throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key security is insufficient'); + } + + let record: StoredDeviceMobileKey; + try { + record = JSON.parse(credentials.password); + } catch (_) { + throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key record is invalid'); + } + if ( + !record || + typeof record !== 'object' || + Object.keys(record).sort().join(',') !== + 'masterFingerprint,network,seedHex,signerPath,version,xpub' || + record.version !== RECORD_VERSION || + record.network !== 'testnet' || + record.signerPath !== RECOVERABLE_MOBILE_KEY_SIGNER_PATH || + typeof record.seedHex !== 'string' || + !/^[0-9a-f]{64}$/.test(record.seedHex) + ) { + throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key record is invalid'); + } + + const signer = deriveDeviceMobileKeyPublic(Buffer.from(record.seedHex, 'hex')); + if (record.masterFingerprint !== signer.masterFingerprint || record.xpub !== signer.xpub) { + throw new DeviceMobileKeyError( + 'INVALID_STORAGE', + 'Stored Mobile Key public data does not match' + ); + } + return signer; +} + +function nativeAdapters(): DeviceMobileKeyAdapters { + // Keep these imports after the preview identity gate. In particular, the + // package's global getRandomValues polyfill can fall back to Math.random in + // Chrome debugging; this service calls its native TurboModule directly. + const { TurboModuleRegistry, Platform } = + require('react-native') as typeof import('react-native'); + const Keychain = require('react-native-keychain') as typeof import('react-native-keychain'); + if (Platform.OS !== 'ios' && Platform.OS !== 'android') { + throw new DeviceMobileKeyError('UNSUPPORTED_PLATFORM', 'Mobile Key requires iOS or Android'); + } + if ( + Platform.OS === 'android' && + (String(Keychain.SECURITY_LEVEL.SECURE_SOFTWARE) !== ANDROID_SECURITY_LEVEL || + Keychain.STORAGE_TYPE.AES_GCM_NO_AUTH !== ANDROID_STORAGE) + ) { + throw new DeviceMobileKeyError('STORAGE_UNAVAILABLE', 'Android secure storage is unavailable'); + } + return { + platform: Platform.OS, + entropy: TurboModuleRegistry.getEnforcing( + 'RNGetRandomValues' + ) as DeviceMobileKeyAdapters['entropy'], + keychain: { + getGenericPassword: (options) => Keychain.getGenericPassword(options), + setGenericPassword: (username, password, options) => { + const nativeOptions = { + service: options.service, + cloudSync: options.cloudSync, + accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED_THIS_DEVICE_ONLY, + ...(Platform.OS === 'android' + ? { + securityLevel: Keychain.SECURITY_LEVEL.SECURE_SOFTWARE, + storage: Keychain.STORAGE_TYPE.AES_GCM_NO_AUTH, + } + : {}), + }; + return Keychain.setGenericPassword(username, password, nativeOptions); + }, + }, + }; +} + +function keychainWriteOptions(service: string, platform: DeviceMobileKeyAdapters['platform']) { + return { + service, + accessible: IOS_ACCESSIBLE, + cloudSync: false as const, + ...(platform === 'android' + ? { securityLevel: ANDROID_SECURITY_LEVEL, storage: ANDROID_STORAGE } + : {}), + }; +} + +async function loadOrCreate( + service: string, + { platform, entropy, keychain }: DeviceMobileKeyAdapters +): Promise { + // A thrown read is never interpreted as absence. A record observed here is + // never reset or replaced. Single-flight only serializes this JS runtime. + const stored = await keychain.getGenericPassword({ service, cloudSync: false }); + if (stored) return parseStoredKey(stored, service, platform); + + const seed = decodeNativeEntropy(entropy.getRandomBase64(32)); + let record: StoredDeviceMobileKey; + try { + const signer = deriveDeviceMobileKeyPublic(seed); + record = { + version: RECORD_VERSION, + network: 'testnet', + signerPath: RECOVERABLE_MOBILE_KEY_SIGNER_PATH, + seedHex: seed.toString('hex'), + masterFingerprint: signer.masterFingerprint, + xpub: signer.xpub, + }; + } finally { + seed.fill(0); + } + + const written = await keychain.setGenericPassword( + KEYCHAIN_USERNAME, + JSON.stringify(record), + keychainWriteOptions(service, platform) + ); + if ( + !written || + written.service !== service || + (platform === 'android' && written.storage !== ANDROID_STORAGE) + ) { + throw new DeviceMobileKeyError('WRITE_FAILED', 'Mobile Key secure storage failed'); + } + + const readback = await keychain.getGenericPassword({ service, cloudSync: false }); + if (!readback) { + throw new DeviceMobileKeyError('READBACK_FAILED', 'Mobile Key secure storage readback failed'); + } + const signer = parseStoredKey(readback, service, platform); + if ( + readback.password !== JSON.stringify(record) || + signer.masterFingerprint !== record.masterFingerprint || + signer.xpub !== record.xpub + ) { + throw new DeviceMobileKeyError( + 'READBACK_MISMATCH', + 'Mobile Key secure storage readback differs' + ); + } + return signer; +} + +const inFlight = new Map>(); + +/** + * Preview-only, testnet-only device key preparation. It does not create a + * wallet, register a Server Key, sign, or expose private material to callers. + */ +export function getOrCreatePreviewDeviceMobileKey( + adapters?: DeviceMobileKeyAdapters +): Promise { + let bundleId: string; + try { + bundleId = DeviceInfo.getBundleId(); + } catch (_) { + bundleId = ''; + } + if ( + typeof bundleId !== 'string' || + getPreviewRuntime( + NativeConfig.KEEPER_PREVIEW, + bundleId, + NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY + ) !== 'preview' + ) { + return Promise.reject( + new DeviceMobileKeyError( + 'PREVIEW_ONLY', + 'Mobile Key service requires the testnet preview app' + ) + ); + } + + const service = `${bundleId}.mobile-key.v1`; + const pending = inFlight.get(service); + if (pending) return pending; + + let chosenAdapters: DeviceMobileKeyAdapters; + try { + chosenAdapters = adapters ?? nativeAdapters(); + } catch (error) { + return Promise.reject( + error instanceof DeviceMobileKeyError + ? error + : new DeviceMobileKeyError( + 'ENTROPY_UNAVAILABLE', + 'Native Mobile Key services are unavailable' + ) + ); + } + const task = loadOrCreate(service, chosenAdapters); + inFlight.set(service, task); + const clear = () => { + if (inFlight.get(service) === task) inFlight.delete(service); + }; + void task.then(clear, clear); + return task; +} diff --git a/tests/preview/recoverableWalletPreview.test.ts b/tests/preview/recoverableWalletPreview.test.ts index bd1df99e0..30562be5b 100644 --- a/tests/preview/recoverableWalletPreview.test.ts +++ b/tests/preview/recoverableWalletPreview.test.ts @@ -7,6 +7,30 @@ import { initialPreviewDraft, reducePreviewDraft, } from '../../src/preview/recoverable-wallet/previewFlow'; +import { + initialSimulatedSetupState, + reduceSimulatedSetup, +} from '../../src/preview/recoverable-wallet/simulatedSetup'; + +describe('Simulated automatic setup', () => { + test('a failed step cannot complete until retried, and retry keeps the same key', () => { + let state = reduceSimulatedSetup(initialSimulatedSetupState, 'SIMULATE_FAILURE'); + expect(state).toBe('mobile-failed'); + expect(reduceSimulatedSetup(state, 'COMPLETE_STEP')).toBe('mobile-failed'); + state = reduceSimulatedSetup(state, 'RETRY'); + expect(state).toBe('adding-mobile'); + state = reduceSimulatedSetup(state, 'COMPLETE_STEP'); + expect(state).toBe('adding-server'); + state = reduceSimulatedSetup(state, 'SIMULATE_FAILURE'); + expect(state).toBe('server-failed'); + expect(reduceSimulatedSetup(state, 'COMPLETE_STEP')).toBe('server-failed'); + state = reduceSimulatedSetup(state, 'RETRY'); + expect(state).toBe('adding-server'); + expect(reduceSimulatedSetup(state, 'COMPLETE_STEP')).toBe('ready'); + expect(reduceSimulatedSetup('ready', 'SHOW_SERVER_FAILURE')).toBe('server-failed'); + expect(reduceSimulatedSetup('ready', 'RETRY')).toBe('ready'); + }); +}); describe('Recoverable Wallet preview isolation', () => { test.each(PREVIEW_BUNDLE_IDS)( diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index e319ba67c..b5ba72d72 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -62,9 +62,7 @@ describe('Recoverable Wallet preview on a small screen', () => { expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('No wallets yet'); expect(screen.queryByTestId('primary-Add Wallet')).toBeNull(); fireEvent.press(screen.getByTestId('wallet-choice-seedless')); - expect(screen.getByTestId('preview-simulation-banner')).toHaveTextContent( - 'Simulated walkthrough' - ); + expect(screen.getByTestId('preview-simulation-banner')).toHaveTextContent('TESTNET DEMO'); expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent( 'Adding… · SIMULATED' ); @@ -112,6 +110,84 @@ describe('Recoverable Wallet preview on a small screen', () => { ); }); + test('simulated Mobile and Server failures pause progress and retry only the failed step', () => { + const screen = render(); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + fireEvent.press(screen.getByTestId('preview-automatic-simulate-failure')); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent('Failed · SIMULATED'); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent( + 'Waiting · SIMULATED' + ); + expect(screen.getByTestId('preview-automatic-error')).toHaveTextContent( + 'SIMULATED FAILURE · Mobile Key setup stopped' + ); + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + true + ); + act(() => jest.advanceTimersByTime(2400)); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent('Failed · SIMULATED'); + fireEvent.press(screen.getByTestId('preview-cancel')); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent('Failed · SIMULATED'); + fireEvent.press(screen.getByTestId('preview-automatic-retry')); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + act(() => jest.advanceTimersByTime(800)); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent('Added · SIMULATED'); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + fireEvent.press(screen.getByTestId('preview-automatic-simulate-failure')); + act(() => jest.advanceTimersByTime(1600)); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent('Failed · SIMULATED'); + expect(screen.getByTestId('preview-automatic-error')).toHaveTextContent( + 'SIMULATED FAILURE · Server Key setup stopped' + ); + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + true + ); + fireEvent.press(screen.getByTestId('preview-cancel')); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent('Failed · SIMULATED'); + fireEvent.press(screen.getByTestId('preview-automatic-retry')); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent('Added · SIMULATED'); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + act(() => jest.advanceTimersByTime(800)); + expect(screen.queryByTestId('preview-automatic-error')).toBeNull(); + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + false + ); + expect(screen.getByTestId('preview-automatic-simulate-failure')).toHaveTextContent( + 'Show Setup Error' + ); + fireEvent.press(screen.getByTestId('preview-automatic-simulate-failure')); + expect(screen.getByTestId('preview-server-key-status')).toHaveTextContent('Failed · SIMULATED'); + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + true + ); + fireEvent.press(screen.getByTestId('preview-automatic-retry')); + act(() => jest.advanceTimersByTime(800)); + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + false + ); + fireEvent.press(screen.getByTestId('primary-Choose Hardware')); + fireEvent.press(screen.getByTestId('preview-hardware-Coldcard')); + fireEvent.press(screen.getByTestId('primary-Continue')); + fireEvent.press(screen.getByTestId('preview-continue-simulation')); + fireEvent.press(screen.getByTestId('primary-Review Policy')); + fireEvent.press(screen.getByTestId('primary-Finish Preview')); + fireEvent.press(screen.getByTestId('preview-start-again')); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + expect(screen.getByTestId('primary-Choose Hardware').props.accessibilityState.disabled).toBe( + true + ); + }); + test('reaches one final review, and resumes hardware after cancel', () => { const screen = render(); fireEvent.press(screen.getByTestId('wallet-choice-seedless')); diff --git a/tests/services/recoverable/deviceMobileKey.test.ts b/tests/services/recoverable/deviceMobileKey.test.ts new file mode 100644 index 000000000..62f77d4be --- /dev/null +++ b/tests/services/recoverable/deviceMobileKey.test.ts @@ -0,0 +1,272 @@ +import { + deriveDeviceMobileKeyPublic, + getOrCreatePreviewDeviceMobileKey, + type DeviceMobileKeyAdapters, +} from 'src/services/wallets/recoverable/deviceMobileKey'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; + +jest.mock('react-native-config', () => ({ + __esModule: true, + default: { KEEPER_PREVIEW: 'true', KEEPER_PREVIEW_TESTNET_ONLY: 'true' }, +})); +jest.mock('react-native-device-info', () => ({ + __esModule: true, + default: { getBundleId: jest.fn(() => 'io.hexawallet.keeper.recoverablepreview') }, +})); + +const previewBundleId = 'io.hexawallet.keeper.recoverablepreview'; +const service = `${previewBundleId}.mobile-key.v1`; +const seed = Buffer.from('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', 'hex'); + +type Stored = false | { service: string; username: string; password: string; storage?: string }; + +function fixture(platform: DeviceMobileKeyAdapters['platform'] = 'ios') { + let stored: Stored = false; + const adapters: DeviceMobileKeyAdapters = { + platform, + entropy: { getRandomBase64: jest.fn(() => seed.toString('base64')) }, + keychain: { + getGenericPassword: jest.fn(async () => stored), + setGenericPassword: jest.fn(async (username, password, options) => { + stored = { service: options.service, username, password, storage: options.storage }; + return { service: options.service, storage: options.storage }; + }), + }, + }; + return { adapters, getStored: () => stored, setStored: (value: Stored) => (stored = value) }; +} + +describe('preview device-generated Mobile Key', () => { + beforeEach(() => { + NativeConfig.KEEPER_PREVIEW = 'true'; + NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY = 'true'; + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue(previewBundleId); + }); + + it('derives a stable testnet BIP48 account tpub and exposes no seed', () => { + const signer = deriveDeviceMobileKeyPublic(seed); + expect(signer).toMatchObject({ + role: 'mobile', + masterFingerprint: '5A3469B6', + derivationPath: "m/48'/1'/0'/2'", + origin: { kind: 'device-generated', version: 1 }, + }); + expect(signer.xpub).toBe( + 'tpubDEhFJsryccF9b2PaR3mgUBVfoYbpVaXsmpK6sonC8cysYcpJzYsZfiwkR9JaoiNWCT9o1HN2bFccb2wMnAXGdKpW6nYQukZMZXfF32RnS6y' + ); + if (signer.origin.kind !== 'device-generated') throw new Error('Unexpected Mobile Key origin'); + expect(signer.origin.sourceId).toBe(`device-generated:${signer.xpub}`); + expect(JSON.stringify(signer)).not.toContain(seed.toString('hex')); + expect(Object.keys(signer)).toEqual([ + 'role', + 'signerType', + 'masterFingerprint', + 'xpub', + 'derivationPath', + 'origin', + ]); + }); + + it.each([Buffer.alloc(0), Buffer.alloc(16), Buffer.alloc(64)])( + 'rejects seeds other than 32 bytes', + (invalid) => { + expect(() => deriveDeviceMobileKeyPublic(invalid)).toThrow('32 bytes'); + } + ); + + it.each([ + { previewFlag: undefined, bundleId: previewBundleId, testnetOnlyFlag: 'true' }, + { previewFlag: 'true', bundleId: 'io.hexawallet.keeper', testnetOnlyFlag: 'true' }, + { previewFlag: 'true', bundleId: previewBundleId, testnetOnlyFlag: undefined }, + ])( + 'rejects any non-preview installed identity before touching adapters', + async (wrongRuntime) => { + NativeConfig.KEEPER_PREVIEW = wrongRuntime.previewFlag; + NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY = wrongRuntime.testnetOnlyFlag; + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue(wrongRuntime.bundleId); + const { adapters } = fixture(); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'PREVIEW_ONLY', + }); + expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); + expect(adapters.keychain.getGenericPassword).not.toHaveBeenCalled(); + } + ); + + it('fails closed if native package identity cannot be read', async () => { + (DeviceInfo.getBundleId as jest.Mock).mockImplementationOnce(() => { + throw new Error('native identity unavailable'); + }); + const { adapters } = fixture(); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'PREVIEW_ONLY', + }); + expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); + expect(adapters.keychain.getGenericPassword).not.toHaveBeenCalled(); + }); + + it('stores once under the exact preview service, reads back, and returns public details only', async () => { + const { adapters, getStored } = fixture(); + const result = await getOrCreatePreviewDeviceMobileKey(adapters); + expect(result.xpub).toMatch(/^tpub/); + expect(JSON.stringify(result)).not.toContain(seed.toString('hex')); + expect(adapters.entropy.getRandomBase64).toHaveBeenCalledWith(32); + expect(adapters.keychain.getGenericPassword).toHaveBeenCalledWith({ + service, + cloudSync: false, + }); + expect(adapters.keychain.setGenericPassword).toHaveBeenCalledWith( + 'recoverable-mobile-key-v1', + expect.any(String), + { + service, + accessible: 'AccessibleWhenUnlockedThisDeviceOnly', + cloudSync: false, + } + ); + expect(JSON.parse((getStored() as Exclude).password)).toMatchObject({ + version: 1, + network: 'testnet', + signerPath: "m/48'/1'/0'/2'", + seedHex: seed.toString('hex'), + xpub: result.xpub, + }); + expect(await getOrCreatePreviewDeviceMobileKey(adapters)).toEqual(result); + expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); + expect(adapters.entropy.getRandomBase64).toHaveBeenCalledTimes(1); + }); + + it('requires Android Keystore-backed software security and AES-GCM storage', async () => { + const { adapters, getStored, setStored } = fixture('android'); + await getOrCreatePreviewDeviceMobileKey(adapters); + expect(adapters.keychain.setGenericPassword).toHaveBeenCalledWith( + 'recoverable-mobile-key-v1', + expect.any(String), + { + service, + accessible: 'AccessibleWhenUnlockedThisDeviceOnly', + cloudSync: false, + securityLevel: 'SECURE_SOFTWARE', + storage: 'KeystoreAESGCM_NoAuth', + } + ); + const stored = getStored() as Exclude; + setStored({ ...stored, storage: 'KeystoreAESCBC' }); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'INVALID_STORAGE', + }); + expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); + }); + + it('never generates or overwrites a corrupt existing record', async () => { + const { adapters, setStored } = fixture(); + setStored({ service, username: 'recoverable-mobile-key-v1', password: '{' }); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'INVALID_STORAGE', + }); + expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); + expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); + }); + + it('does not replace a stored key whose public data disagrees with the seed', async () => { + const { adapters, getStored, setStored } = fixture(); + await getOrCreatePreviewDeviceMobileKey(adapters); + const existing = getStored() as Exclude; + const record = JSON.parse(existing.password); + record.xpub = 'tpubcorrupted'; + setStored({ ...existing, password: JSON.stringify(record) }); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'INVALID_STORAGE', + }); + expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); + expect(adapters.entropy.getRandomBase64).toHaveBeenCalledTimes(1); + }); + + it('does not generate when the keychain read throws', async () => { + const { adapters } = fixture(); + adapters.keychain.getGenericPassword = jest.fn(async () => { + throw new Error('locked'); + }); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toThrow('locked'); + expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); + expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); + }); + + it('fails closed when the native entropy call fails or returns malformed data', async () => { + const { adapters } = fixture(); + adapters.entropy.getRandomBase64 = jest.fn(() => { + throw new Error('native unavailable'); + }); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toThrow('native unavailable'); + expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); + + adapters.entropy.getRandomBase64 = jest.fn(() => 'not base64'); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'INVALID_ENTROPY', + }); + expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); + }); + + it('does not report success on failed write or failed readback', async () => { + const { adapters } = fixture(); + adapters.keychain.setGenericPassword = jest.fn(async () => false); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'WRITE_FAILED', + }); + + let reads = 0; + adapters.keychain.getGenericPassword = jest.fn(async () => { + reads += 1; + return false; + }); + adapters.keychain.setGenericPassword = jest.fn(async () => ({ service })); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'READBACK_FAILED', + }); + expect(reads).toBe(2); + }); + + it('rejects a different key returned by secure-storage readback', async () => { + const { adapters } = fixture(); + let reads = 0; + adapters.keychain.getGenericPassword = jest.fn(async () => { + reads += 1; + return reads === 1 + ? false + : { + service, + username: 'recoverable-mobile-key-v1', + password: JSON.stringify({ + version: 1, + network: 'testnet', + signerPath: "m/48'/1'/0'/2'", + seedHex: Buffer.alloc(32, 1).toString('hex'), + masterFingerprint: deriveDeviceMobileKeyPublic(Buffer.alloc(32, 1)).masterFingerprint, + xpub: deriveDeviceMobileKeyPublic(Buffer.alloc(32, 1)).xpub, + }), + }; + }); + await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + code: 'READBACK_MISMATCH', + }); + }); + + it('shares one in-process creation across concurrent callers', async () => { + const { adapters, getStored } = fixture(); + let releaseRead: (value: Stored) => void = () => undefined; + adapters.keychain.getGenericPassword = jest + .fn() + .mockImplementationOnce(() => new Promise((resolve) => (releaseRead = resolve))) + .mockImplementation(async () => getStored()); + + const first = getOrCreatePreviewDeviceMobileKey(adapters); + const second = getOrCreatePreviewDeviceMobileKey(adapters); + expect(first).toBe(second); + expect(adapters.keychain.getGenericPassword).toHaveBeenCalledTimes(1); + releaseRead(false); + expect(await first).toEqual(await second); + expect(adapters.entropy.getRandomBase64).toHaveBeenCalledTimes(1); + expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); + }); +}); From 86f4be0265f37a9ee7ebc2f9c5f6a2ec97ada1d6 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 17:09:06 +0530 Subject: [PATCH 11/31] Add preview-only native Mobile Key store and public hardware import --- .../KeeperPreviewMobileKeyModule.kt | 167 ++++++++++ .../KeeperPreviewMobileKeyPackage.kt | 17 ++ .../java/com/hexa_keeper/MainApplication.kt | 4 +- docs/preview/recoverable-wallet/README.md | 8 +- .../recoverable-wallet/native-preview.md | 2 + ios/hexa_keeper.xcodeproj/project.pbxproj | 12 + .../KeeperPreviewMobileKey.m | 112 +++++++ .../wallets/recoverable/deviceMobileKey.ts | 256 +++------------- .../recoverable/hardwarePublicImport.ts | 176 +++++++++++ .../wallets/recoverable/policyDraft.ts | 7 +- .../recoverable/deviceMobileKey.test.ts | 287 +++++------------- .../recoverable/hardwarePublicImport.test.ts | 282 +++++++++++++++++ 12 files changed, 901 insertions(+), 429 deletions(-) create mode 100644 android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt create mode 100644 android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyPackage.kt create mode 100644 ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m create mode 100644 src/services/wallets/recoverable/hardwarePublicImport.ts create mode 100644 tests/services/recoverable/hardwarePublicImport.test.ts diff --git a/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt new file mode 100644 index 000000000..e3bc7931c --- /dev/null +++ b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt @@ -0,0 +1,167 @@ +package com.hexa_keeper + +import android.util.AtomicFile +import android.util.Base64 +import com.facebook.react.bridge.Promise +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReactContextBaseJavaModule +import com.facebook.react.bridge.ReactMethod +import io.hexawallet.keeper.BuildConfig +import java.io.File +import java.io.RandomAccessFile +import java.security.KeyStore +import java.security.MessageDigest +import java.security.SecureRandom +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties + +/** A device-only seed store available exclusively in the separate testnet preview app. */ +class KeeperPreviewMobileKeyModule( + private val context: ReactApplicationContext +) : ReactContextBaseJavaModule(context) { + override fun getName() = "KeeperPreviewMobileKey" + + @ReactMethod + fun getOrCreateSeedBase64(promise: Promise) { + if (!BuildConfig.IS_RECOVERABLE_PREVIEW || context.packageName != PREVIEW_PACKAGE) { + promise.reject("PREVIEW_ONLY", "Mobile Key requires the testnet preview app") + return + } + + try { + // The monitor protects threads; the file lock protects a second app process. + val encoded = synchronized(processLock) { + val directory = context.noBackupFilesDir + if (!directory.isDirectory) throw IllegalStateException("No-backup storage unavailable") + RandomAccessFile(File(directory, LOCK_FILE), "rw").use { lockFile -> + lockFile.channel.use { channel -> + channel.lock().use { getOrCreateLocked(directory) } + } + } + } + promise.resolve(encoded) + } catch (_: Exception) { + // Never replace an unreadable, corrupted, or inaccessible existing key. + promise.reject("MOBILE_KEY_STORAGE_UNAVAILABLE", "Mobile Key secure storage is unavailable") + } + } + + private fun getOrCreateLocked(directory: File): String { + val seedFile = File(directory, SEED_FILE) + val atomicFile = AtomicFile(seedFile) + // A lone .new file is an interrupted AtomicFile write, not an empty store. + // Never replace a possible prior seed after a crash. + val hasAnyRecord = seedFile.exists() || + File(seedFile.path + ".bak").exists() || File(seedFile.path + ".new").exists() + val key = getOrCreateEncryptionKey(hasAnyRecord) + + if (hasAnyRecord) { + val seed = decrypt(atomicFile.readFully(), key) + return try { + Base64.encodeToString(seed, Base64.NO_WRAP) + } finally { + seed.fill(0) + } + } + + val seed = ByteArray(SEED_LENGTH) + SecureRandom().nextBytes(seed) + try { + val ciphertext = encrypt(seed, key) + val stream = atomicFile.startWrite() + try { + stream.write(ciphertext) + atomicFile.finishWrite(stream) + } catch (error: Exception) { + atomicFile.failWrite(stream) + throw error + } + + // Do not expose a newly generated seed unless durable storage reads it back. + val readback = decrypt(atomicFile.readFully(), key) + return try { + if (!MessageDigest.isEqual(seed, readback)) { + throw IllegalStateException("Mobile Key readback differs") + } + Base64.encodeToString(seed, Base64.NO_WRAP) + } finally { + readback.fill(0) + } + } finally { + seed.fill(0) + } + } + + private fun getOrCreateEncryptionKey(recordExists: Boolean): SecretKey { + val keyStore = KeyStore.getInstance("AndroidKeyStore") + keyStore.load(null) + val existing = keyStore.getKey(KEY_ALIAS, null) + if (existing != null) { + // The alias can precede the first durable seed write. A crash in + // that window is ambiguous, so require a manual preview reset. + if (!recordExists) throw IllegalStateException("Mobile Key record is missing") + return existing as? SecretKey + ?: throw IllegalStateException("Mobile Key encryption key is invalid") + } + if (recordExists || keyStore.containsAlias(KEY_ALIAS)) { + throw IllegalStateException("Mobile Key encryption key is missing") + } + + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + generator.init( + KeyGenParameterSpec.Builder( + KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .setRandomizedEncryptionRequired(true) + .setUserAuthenticationRequired(false) + .build() + ) + return generator.generateKey() + } + + private fun encrypt(seed: ByteArray, key: SecretKey): ByteArray { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, key) + cipher.updateAAD(PREVIEW_PACKAGE.toByteArray(Charsets.UTF_8)) + val iv = cipher.iv + if (iv.size != IV_LENGTH) throw IllegalStateException("Invalid Mobile Key nonce") + val encrypted = cipher.doFinal(seed) + return byteArrayOf(RECORD_VERSION) + iv + encrypted + } + + private fun decrypt(record: ByteArray, key: SecretKey): ByteArray { + if (record.size != 1 + IV_LENGTH + SEED_LENGTH + TAG_LENGTH || + record[0] != RECORD_VERSION + ) { + throw IllegalStateException("Invalid Mobile Key record") + } + val iv = record.copyOfRange(1, 1 + IV_LENGTH) + val encrypted = record.copyOfRange(1 + IV_LENGTH, record.size) + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv)) + cipher.updateAAD(PREVIEW_PACKAGE.toByteArray(Charsets.UTF_8)) + val seed = cipher.doFinal(encrypted) + if (seed.size != SEED_LENGTH) throw IllegalStateException("Invalid Mobile Key seed") + return seed + } + + private companion object { + const val PREVIEW_PACKAGE = "io.hexawallet.keeper.recoverablepreview" + const val KEY_ALIAS = "$PREVIEW_PACKAGE.mobile-key.v1" + const val SEED_FILE = "keeper-preview-mobile-key-v1.bin" + const val LOCK_FILE = "keeper-preview-mobile-key-v1.lock" + const val SEED_LENGTH = 32 + const val IV_LENGTH = 12 + const val TAG_LENGTH = 16 + const val RECORD_VERSION: Byte = 1 + val processLock = Any() + } +} diff --git a/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyPackage.kt b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyPackage.kt new file mode 100644 index 000000000..1078a1c61 --- /dev/null +++ b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyPackage.kt @@ -0,0 +1,17 @@ +package com.hexa_keeper + +import android.view.View +import com.facebook.react.ReactPackage +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.uimanager.ReactShadowNode +import com.facebook.react.uimanager.ViewManager + +class KeeperPreviewMobileKeyPackage : ReactPackage { + override fun createNativeModules(reactContext: ReactApplicationContext): MutableList = + mutableListOf(KeeperPreviewMobileKeyModule(reactContext)) + + override fun createViewManagers( + reactContext: ReactApplicationContext + ): MutableList>> = mutableListOf() +} diff --git a/android/app/src/main/java/com/hexa_keeper/MainApplication.kt b/android/app/src/main/java/com/hexa_keeper/MainApplication.kt index 9c0628e36..024ba75f7 100644 --- a/android/app/src/main/java/com/hexa_keeper/MainApplication.kt +++ b/android/app/src/main/java/com/hexa_keeper/MainApplication.kt @@ -15,6 +15,7 @@ import android.content.Context import com.facebook.react.ReactInstanceManager import com.hexa_keeper.CloudBackupPackage import com.hexa_keeper.KeepScreenAwakePackage +import com.hexa_keeper.KeeperPreviewMobileKeyPackage import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; @@ -29,7 +30,8 @@ class MainApplication : Application(), ReactApplication { // Packages that cannot be autolinked yet can be added manually here, for example: add(KeepScreenAwakePackage()) // Preview credentials and Drive scope are deliberately not provisioned yet. - if (!BuildConfig.IS_RECOVERABLE_PREVIEW) add(CloudBackupPackage()) + if (BuildConfig.IS_RECOVERABLE_PREVIEW) add(KeeperPreviewMobileKeyPackage()) + else add(CloudBackupPackage()) } override fun getJSMainModuleName(): String = "index" diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index e5e54ce49..b82ba5119 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -12,7 +12,7 @@ Status (9 October 2026): **isolated client preview and direct three-choice empty | Evidence | Current result | | --- | --- | | Simulated client flow | Automated walkthrough covers four hardware choices, cancel/resume, connection error, inheritance choice, and final review. | -| Startup boundary and related regressions | 98 focused Jest tests pass across 13 preview and related service suites. | +| Startup boundary and related regressions | 108 focused Jest tests pass across 14 preview and related service suites. | | Native build | Android arm64 debug APK built with embedded JS, installed and launched on an arm64 emulator; iOS scheme configuration inspected, build pending. | | Small-screen rendering | Android emulator walkthrough passed at 320dp width and 1.6× system font: statuses, four hardware choices, simulated error, inheritance, review, and completion remained scrollable and actionable. The Jest content check alone does not establish rendered layout. | | Physical devices and production side-by-side installation | Production v2.6.3 and Preview co-installed and launched on the emulator. Physical installation and cross-app storage isolation are pending. | @@ -25,14 +25,14 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr - The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Single-Key Wallet** (phone or signing device next), prominent **Seedless Wallet**, and **Custom Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. The labels describe setup paths, without a “Featured” badge or a blanket seed-word promise on the card. Single-Key, Custom, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. - Selecting Seedless immediately starts a compact, simulated progress screen rather than a mandatory introduction: Mobile Key then Server Key status labels advance in order, Hardware Key waits for the user, and **Choose Hardware** enables only after both demo steps. “How it works” is optional in-flow detail; the complete policy remains a required review before any real wallet could be created. The timer changes labels only: it creates no key, backup, server registration, or wallet. A future real “Added” status must wait for verified secure Mobile Key persistence or Server Key registration, respectively; elapsed time cannot establish readiness. - The default Seedless design calls for an independently generated Mobile Key and no new seed words for the user to record. Derivation from Keeper's existing 12-word Recovery Key remains an **optional creation path**, not a setup prerequisite or chooser message. The isolated BIP85 helper reserves a versioned child range starting at index 1,000,000; Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Seedless. Its pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. A Recovery Key cannot recreate a separately generated Mobile Key by derivation alone; that would require a reviewed encrypted backup or wrapping design. -- A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. Its 2-of-3 and delayed 2-of-4 results are explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). +- A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. A separate pure importer accepts public Coldcard/Jade BIP48 testnet exports and marks both the device and policy **not verified**; it does not open a device or connect to the UI. The 2-of-3 and delayed 2-of-4 policy results remain explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). - A client-only Recovery Contact state model covers encrypted-cloud readback receipts, offline retry, invitation/request expiry, approval/decline, and optional recovery-code gating. It stops before cryptographic enrollment or restoration. No contact key, encrypted backup, native cloud container, or independent exchange channel exists yet. See [recovery-contact.md](recovery-contact.md). - The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. - Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. -The latest client code passed **98 Jest tests across 13 focused suites** covering the direct empty Wallets entry, simulated Mobile/Server failure and retry, Add Wallet chooser, preview isolation, hardware-dependent inheritance gating, Recovery Key education gate, device Mobile Key derivation and storage error handling, key-origin policy draft, contact states, and Recovery Key migration. The latest arm64 APK embeds this chooser, shorter copy, and simulated setup error/retry states. An Android emulator walkthrough at 320dp and 1.6× system font confirmed that the three-choice landing, Mobile/Server statuses, hardware action, persistent setup error sample, and retry remain reachable by scrolling. The complete hardware, inheritance, and final-review walkthrough at that size was recorded against the preceding package; those flow stages did not change in this package. The temporary local Metro symlink adjustment was removed after packaging. +The latest client code passed **108 Jest tests across 14 focused suites** covering the direct empty Wallets entry, simulated Mobile/Server failure and retry, Add Wallet chooser, preview isolation, hardware-dependent inheritance gating, Recovery Key education gate, native Mobile Key bridge error handling, public Coldcard/Jade export validation, key-origin policy draft, contact states, and Recovery Key migration. The latest arm64 APK embeds this chooser, shorter copy, simulated setup error/retry states, and Android's preview-only native Mobile Key module. An Android emulator walkthrough at 320dp and 1.6× system font confirmed that the three-choice landing, Mobile/Server statuses, hardware action, persistent setup error sample, and retry remain reachable by scrolling. The complete hardware, inheritance, and final-review walkthrough at that size was recorded against the preceding package; those flow stages did not change in this package. The temporary local Metro symlink adjustment was removed after packaging. -The separate `deviceMobileKey.ts` service is **not called by the preview UI or wallet creation**. It prepares a testnet BIP48 public Mobile signer from native random bytes and a preview-scoped Keychain record, with a read-back check. This is preparation for a real flow, not proof of a safe fundable key: the installed Keychain library does not provide atomic create-if-absent across runtimes, and the current JavaScript identity check needs a native preview-flavor guard before key creation is connected to real wallet readiness. Native Keychain behavior, backup, restoration, and device isolation remain unverified. +The separate `deviceMobileKey.ts` service is **not called by the preview UI or wallet creation**. It can derive a testnet BIP48 public Mobile signer from the new preview-only native seed store. Android uses a Keystore-encrypted no-backup record under a file lock; iOS uses a non-sync, ThisDeviceOnly Keychain record with create-if-absent. Both native modules check the installed preview identity, and Android preview compilation passed. This is preparation for a real flow, not proof of a safe fundable key: native storage has not been runtime-tested, iOS has not been fully built, the seed crosses the native-to-JavaScript bridge for derivation, and key continuity after reinstall must be tied to an existing wallet policy before creation can be connected to real readiness. Encrypted backup and recovery remain absent. ## Owner decision (8 October 2026) diff --git a/docs/preview/recoverable-wallet/native-preview.md b/docs/preview/recoverable-wallet/native-preview.md index 13e92024d..496ff3853 100644 --- a/docs/preview/recoverable-wallet/native-preview.md +++ b/docs/preview/recoverable-wallet/native-preview.md @@ -9,6 +9,8 @@ The preview runs the simulated Recoverable Wallet flow only. It creates no walle Both builds use the checked-in `.env.recoverable-preview` file. It sets `KEEPER_PREVIEW=true`, `KEEPER_PREVIEW_TESTNET_ONLY=true` and local unreachable service URLs. The preview entry also checks the exact native bundle/application ID before showing the flow; mismatches show a locked error screen. The preview runtime does not initialize the normal Keeper app or its wallet store. +The preview-only native Mobile Key module is registered only in the Android `recoverablePreview` flavor and compiled only in the iOS preview scheme's development target. It checks the exact installed app ID again before using device-only secure storage. Its JavaScript service remains uncalled by the walkthrough; the visible Mobile Key status is still simulated. Android native code compiles, while iOS compilation and both platforms' runtime storage behavior remain unverified. Before any real wallet can be funded, test create/load, interrupted writes, corruption, reinstall continuity, and seed exposure through the JavaScript bridge, then establish recovery and policy-bound key identity. + ## Build and install From the repository root after installing JS dependencies: diff --git a/ios/hexa_keeper.xcodeproj/project.pbxproj b/ios/hexa_keeper.xcodeproj/project.pbxproj index e5b76d957..b1ce12369 100644 --- a/ios/hexa_keeper.xcodeproj/project.pbxproj +++ b/ios/hexa_keeper.xcodeproj/project.pbxproj @@ -8,6 +8,7 @@ /* Begin PBXBuildFile section */ 00E356F31AD99517003FC87E /* hexa_keeperTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* hexa_keeperTests.m */; }; + A7E11A000000000000000002 /* KeeperPreviewMobileKey.m in Sources */ = {isa = PBXBuildFile; fileRef = A7E11A000000000000000001 /* KeeperPreviewMobileKey.m */; }; 02EFDECE01B760848CCFE2A3 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = CFF59ED1275C7DD527FF60A7 /* PrivacyInfo.xcprivacy */; }; 03A1CD3648C24AEB830A5CF4 /* Inter-LightItalic.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 18A6256AB47842ABA0F4BF8D /* Inter-LightItalic.ttf */; }; 13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.mm */; }; @@ -64,6 +65,7 @@ 00E356EE1AD99517003FC87E /* hexa_keeperTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = hexa_keeperTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 00E356F21AD99517003FC87E /* hexa_keeperTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = hexa_keeperTests.m; sourceTree = ""; }; + A7E11A000000000000000001 /* KeeperPreviewMobileKey.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = KeeperPreviewMobileKey.m; sourceTree = ""; }; 08FBE774D80E15AF57C7A99D /* Pods-hexa_keeper.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-hexa_keeper.debug.xcconfig"; path = "Target Support Files/Pods-hexa_keeper/Pods-hexa_keeper.debug.xcconfig"; sourceTree = ""; }; 13B07F961A680F5B00A75B9A /* hexa_keeper.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = hexa_keeper.app; sourceTree = BUILT_PRODUCTS_DIR; }; 13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = hexa_keeper/AppDelegate.h; sourceTree = ""; }; @@ -219,6 +221,7 @@ isa = PBXGroup; children = ( 35112D4E2BD7DA7600343479 /* cloudbackup */, + A7E11A000000000000000003 /* recoverablePreviewMobileKey */, F4F7F75B2A0558220027FE4C /* keepScreenAwake */, 1F9F461229BF9D5D006C129F /* whirlpool */, 13B07FAE1A68108700A75B9A /* hexa_keeper */, @@ -236,6 +239,14 @@ tabWidth = 2; usesTabs = 0; }; + A7E11A000000000000000003 /* recoverablePreviewMobileKey */ = { + isa = PBXGroup; + children = ( + A7E11A000000000000000001 /* KeeperPreviewMobileKey.m */, + ); + path = recoverablePreviewMobileKey; + sourceTree = ""; + }; 83CBBA001A601CBA00E9B192 /* Products */ = { isa = PBXGroup; children = ( @@ -683,6 +694,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + A7E11A000000000000000002 /* KeeperPreviewMobileKey.m in Sources */, 35112D552BD7DB3000343479 /* cloudbackup.m in Sources */, 35112D512BD7DAE700343479 /* CloudBackupHelper.swift in Sources */, F49B77E32848DF5200F9AFBD /* AppDelegate.mm in Sources */, diff --git a/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m b/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m new file mode 100644 index 000000000..684f1eb7e --- /dev/null +++ b/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m @@ -0,0 +1,112 @@ +#import +#import + +#if defined(KEEPER_RECOVERABLE_PREVIEW) && KEEPER_RECOVERABLE_PREVIEW + +#import +#import + +static NSString *const KeeperPreviewBundleID = @"io.hexawallet.hexakeeper.recoverablepreview"; +static NSString *const KeeperPreviewSeedService = @"io.hexawallet.hexakeeper.recoverablepreview.mobile-key.v1"; +static NSString *const KeeperPreviewSeedAccount = @"seed-v1"; + +static NSDictionary *KeeperPreviewSeedQuery(void) +{ + return @{ + (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrService: KeeperPreviewSeedService, + (__bridge id)kSecAttrAccount: KeeperPreviewSeedAccount, + (__bridge id)kSecAttrSynchronizable: @NO, + (__bridge id)kSecReturnData: @YES, + (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne, + }; +} + +static OSStatus KeeperPreviewReadSeed(NSData **seed) +{ + CFTypeRef result = NULL; + OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)KeeperPreviewSeedQuery(), &result); + if (status != errSecSuccess) { + if (result != NULL) CFRelease(result); + return status; + } + if (result == NULL || CFGetTypeID(result) != CFDataGetTypeID()) { + if (result != NULL) CFRelease(result); + return errSecDecode; + } + *seed = CFBridgingRelease(result); + return [(*seed) length] == 32 ? errSecSuccess : errSecDecode; +} + +@interface KeeperPreviewMobileKey : NSObject +@end + +@implementation KeeperPreviewMobileKey + +RCT_EXPORT_MODULE(KeeperPreviewMobileKey); + ++ (BOOL)requiresMainQueueSetup +{ + return NO; +} + +RCT_EXPORT_METHOD(getOrCreateSeedBase64:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) +{ + NSBundle *bundle = [NSBundle mainBundle]; + if (![[bundle bundleIdentifier] isEqualToString:KeeperPreviewBundleID] || + ![[bundle objectForInfoDictionaryKey:@"KeeperRecoverablePreview"] isEqual:@YES]) { + reject(@"PREVIEW_ONLY", @"Mobile Key requires the testnet preview app", nil); + return; + } + + @synchronized([KeeperPreviewMobileKey class]) { + NSData *stored = nil; + OSStatus status = KeeperPreviewReadSeed(&stored); + if (status == errSecSuccess) { + resolve([stored base64EncodedStringWithOptions:0]); + return; + } + if (status != errSecItemNotFound) { + reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); + return; + } + + NSMutableData *created = [NSMutableData dataWithLength:32]; + if (SecRandomCopyBytes(kSecRandomDefault, created.length, created.mutableBytes) != errSecSuccess) { + reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); + return; + } + + NSDictionary *item = @{ + (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrService: KeeperPreviewSeedService, + (__bridge id)kSecAttrAccount: KeeperPreviewSeedAccount, + (__bridge id)kSecAttrSynchronizable: @NO, + (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenUnlockedThisDeviceOnly, + (__bridge id)kSecValueData: created, + }; + status = SecItemAdd((__bridge CFDictionaryRef)item, NULL); + if (status != errSecSuccess && status != errSecDuplicateItem) { + memset(created.mutableBytes, 0, created.length); + reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); + return; + } + + NSData *readback = nil; + OSStatus readStatus = KeeperPreviewReadSeed(&readback); + if (readStatus != errSecSuccess || + (status == errSecSuccess && ![readback isEqualToData:created])) { + memset(created.mutableBytes, 0, created.length); + reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); + return; + } + // SecItemAdd is create-if-absent. On a duplicate, use the winner's seed. + resolve([readback base64EncodedStringWithOptions:0]); + memset(created.mutableBytes, 0, created.length); + } +} + +@end + +#endif diff --git a/src/services/wallets/recoverable/deviceMobileKey.ts b/src/services/wallets/recoverable/deviceMobileKey.ts index ca61aeeb9..54c66ede4 100644 --- a/src/services/wallets/recoverable/deviceMobileKey.ts +++ b/src/services/wallets/recoverable/deviceMobileKey.ts @@ -10,52 +10,11 @@ import { RECOVERABLE_MOBILE_KEY_SIGNER_PATH } from '../operations/recoverable/mo import type { RecoverableMobileSigner } from './policyDraft'; const bip32 = BIP32Factory(ecc); - const RECORD_VERSION = 1 as const; -const KEYCHAIN_USERNAME = 'recoverable-mobile-key-v1'; -const IOS_ACCESSIBLE = 'AccessibleWhenUnlockedThisDeviceOnly' as const; -const ANDROID_SECURITY_LEVEL = 'SECURE_SOFTWARE' as const; -const ANDROID_STORAGE = 'KeystoreAESGCM_NoAuth' as const; - -interface StoredCredentials { - service: string; - username: string; - password: string; - storage?: string; -} -/** Narrow seams allow fail-closed native calls to be tested without a device. */ +/** A narrow seam for native preview key creation; tests never touch a real key store. */ export interface DeviceMobileKeyAdapters { - platform: 'ios' | 'android'; - entropy: { - getRandomBase64(byteLength: number): string; - }; - keychain: { - getGenericPassword(options: { - service: string; - cloudSync: false; - }): Promise; - setGenericPassword( - username: string, - password: string, - options: { - service: string; - accessible: typeof IOS_ACCESSIBLE; - cloudSync: false; - securityLevel?: typeof ANDROID_SECURITY_LEVEL; - storage?: typeof ANDROID_STORAGE; - } - ): Promise; - }; -} - -interface StoredDeviceMobileKey { - version: typeof RECORD_VERSION; - network: 'testnet'; - signerPath: typeof RECOVERABLE_MOBILE_KEY_SIGNER_PATH; - seedHex: string; - masterFingerprint: string; - xpub: string; + getOrCreateSeedBase64(): Promise; } export class DeviceMobileKeyError extends Error { @@ -65,7 +24,7 @@ export class DeviceMobileKeyError extends Error { } } -/** Pure public derivation. The caller retains the seed; this function never returns it. */ +/** Return only public policy input. Private seed bytes are not part of the result. */ export function deriveDeviceMobileKeyPublic(seed: Uint8Array): RecoverableMobileSigner { if (!(seed instanceof Uint8Array) || seed.length !== 32) { throw new DeviceMobileKeyError('INVALID_SEED', 'Mobile Key seed must be 32 bytes'); @@ -81,186 +40,49 @@ export function deriveDeviceMobileKeyPublic(seed: Uint8Array): RecoverableMobile origin: { kind: 'device-generated', version: RECORD_VERSION, - // The tpub is public and already returned. It is a stable, unique source reference. sourceId: `device-generated:${xpub}`, }, }; } -function decodeNativeEntropy(base64: string): Buffer { +function decodeNativeSeed(base64: string): Buffer { if (typeof base64 !== 'string') { - throw new DeviceMobileKeyError( - 'ENTROPY_UNAVAILABLE', - 'Native secure random bytes are unavailable' - ); + throw new DeviceMobileKeyError('INVALID_NATIVE_SEED', 'Native Mobile Key is invalid'); } const seed = Buffer.from(base64, 'base64'); if (seed.length !== 32 || seed.toString('base64') !== base64) { seed.fill(0); - throw new DeviceMobileKeyError('INVALID_ENTROPY', 'Native secure random bytes were invalid'); + throw new DeviceMobileKeyError('INVALID_NATIVE_SEED', 'Native Mobile Key is invalid'); } return seed; } -function parseStoredKey( - credentials: StoredCredentials, - service: string, - platform: DeviceMobileKeyAdapters['platform'] -): RecoverableMobileSigner { - if (credentials.service !== service || credentials.username !== KEYCHAIN_USERNAME) { - throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key identity is invalid'); - } - if (platform === 'android' && credentials.storage !== ANDROID_STORAGE) { - throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key security is insufficient'); - } - - let record: StoredDeviceMobileKey; - try { - record = JSON.parse(credentials.password); - } catch (_) { - throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key record is invalid'); - } - if ( - !record || - typeof record !== 'object' || - Object.keys(record).sort().join(',') !== - 'masterFingerprint,network,seedHex,signerPath,version,xpub' || - record.version !== RECORD_VERSION || - record.network !== 'testnet' || - record.signerPath !== RECOVERABLE_MOBILE_KEY_SIGNER_PATH || - typeof record.seedHex !== 'string' || - !/^[0-9a-f]{64}$/.test(record.seedHex) - ) { - throw new DeviceMobileKeyError('INVALID_STORAGE', 'Stored Mobile Key record is invalid'); - } - - const signer = deriveDeviceMobileKeyPublic(Buffer.from(record.seedHex, 'hex')); - if (record.masterFingerprint !== signer.masterFingerprint || record.xpub !== signer.xpub) { - throw new DeviceMobileKeyError( - 'INVALID_STORAGE', - 'Stored Mobile Key public data does not match' - ); - } - return signer; -} - -function nativeAdapters(): DeviceMobileKeyAdapters { - // Keep these imports after the preview identity gate. In particular, the - // package's global getRandomValues polyfill can fall back to Math.random in - // Chrome debugging; this service calls its native TurboModule directly. - const { TurboModuleRegistry, Platform } = - require('react-native') as typeof import('react-native'); - const Keychain = require('react-native-keychain') as typeof import('react-native-keychain'); +function nativeAdapter(): DeviceMobileKeyAdapters { + // The native module itself checks the compiled preview flavor and installed + // app ID, and atomically creates or loads a device-only seed. There is no JS + // random-values or read-then-overwrite Keychain fallback. + const { NativeModules, Platform } = require('react-native') as typeof import('react-native'); if (Platform.OS !== 'ios' && Platform.OS !== 'android') { throw new DeviceMobileKeyError('UNSUPPORTED_PLATFORM', 'Mobile Key requires iOS or Android'); } - if ( - Platform.OS === 'android' && - (String(Keychain.SECURITY_LEVEL.SECURE_SOFTWARE) !== ANDROID_SECURITY_LEVEL || - Keychain.STORAGE_TYPE.AES_GCM_NO_AUTH !== ANDROID_STORAGE) - ) { - throw new DeviceMobileKeyError('STORAGE_UNAVAILABLE', 'Android secure storage is unavailable'); - } - return { - platform: Platform.OS, - entropy: TurboModuleRegistry.getEnforcing( - 'RNGetRandomValues' - ) as DeviceMobileKeyAdapters['entropy'], - keychain: { - getGenericPassword: (options) => Keychain.getGenericPassword(options), - setGenericPassword: (username, password, options) => { - const nativeOptions = { - service: options.service, - cloudSync: options.cloudSync, - accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED_THIS_DEVICE_ONLY, - ...(Platform.OS === 'android' - ? { - securityLevel: Keychain.SECURITY_LEVEL.SECURE_SOFTWARE, - storage: Keychain.STORAGE_TYPE.AES_GCM_NO_AUTH, - } - : {}), - }; - return Keychain.setGenericPassword(username, password, nativeOptions); - }, - }, - }; -} - -function keychainWriteOptions(service: string, platform: DeviceMobileKeyAdapters['platform']) { - return { - service, - accessible: IOS_ACCESSIBLE, - cloudSync: false as const, - ...(platform === 'android' - ? { securityLevel: ANDROID_SECURITY_LEVEL, storage: ANDROID_STORAGE } - : {}), - }; -} - -async function loadOrCreate( - service: string, - { platform, entropy, keychain }: DeviceMobileKeyAdapters -): Promise { - // A thrown read is never interpreted as absence. A record observed here is - // never reset or replaced. Single-flight only serializes this JS runtime. - const stored = await keychain.getGenericPassword({ service, cloudSync: false }); - if (stored) return parseStoredKey(stored, service, platform); - - const seed = decodeNativeEntropy(entropy.getRandomBase64(32)); - let record: StoredDeviceMobileKey; - try { - const signer = deriveDeviceMobileKeyPublic(seed); - record = { - version: RECORD_VERSION, - network: 'testnet', - signerPath: RECOVERABLE_MOBILE_KEY_SIGNER_PATH, - seedHex: seed.toString('hex'), - masterFingerprint: signer.masterFingerprint, - xpub: signer.xpub, - }; - } finally { - seed.fill(0); - } - - const written = await keychain.setGenericPassword( - KEYCHAIN_USERNAME, - JSON.stringify(record), - keychainWriteOptions(service, platform) - ); - if ( - !written || - written.service !== service || - (platform === 'android' && written.storage !== ANDROID_STORAGE) - ) { - throw new DeviceMobileKeyError('WRITE_FAILED', 'Mobile Key secure storage failed'); - } - - const readback = await keychain.getGenericPassword({ service, cloudSync: false }); - if (!readback) { - throw new DeviceMobileKeyError('READBACK_FAILED', 'Mobile Key secure storage readback failed'); - } - const signer = parseStoredKey(readback, service, platform); - if ( - readback.password !== JSON.stringify(record) || - signer.masterFingerprint !== record.masterFingerprint || - signer.xpub !== record.xpub - ) { + const module = NativeModules.KeeperPreviewMobileKey as DeviceMobileKeyAdapters | undefined; + if (!module || typeof module.getOrCreateSeedBase64 !== 'function') { throw new DeviceMobileKeyError( - 'READBACK_MISMATCH', - 'Mobile Key secure storage readback differs' + 'NATIVE_KEY_UNAVAILABLE', + 'Native Mobile Key store is unavailable' ); } - return signer; + return module; } const inFlight = new Map>(); /** - * Preview-only, testnet-only device key preparation. It does not create a - * wallet, register a Server Key, sign, or expose private material to callers. + * Preview-only, testnet-only key preparation. This is intentionally not wired + * to wallet creation, signing, backup, or the simulated "Added" status. */ export function getOrCreatePreviewDeviceMobileKey( - adapters?: DeviceMobileKeyAdapters + adapter?: DeviceMobileKeyAdapters ): Promise { let bundleId: string; try { @@ -277,34 +99,36 @@ export function getOrCreatePreviewDeviceMobileKey( ) !== 'preview' ) { return Promise.reject( - new DeviceMobileKeyError( - 'PREVIEW_ONLY', - 'Mobile Key service requires the testnet preview app' - ) + new DeviceMobileKeyError('PREVIEW_ONLY', 'Mobile Key requires the testnet preview app') ); } - const service = `${bundleId}.mobile-key.v1`; - const pending = inFlight.get(service); + const pending = inFlight.get(bundleId); if (pending) return pending; - let chosenAdapters: DeviceMobileKeyAdapters; + let chosen: DeviceMobileKeyAdapters; try { - chosenAdapters = adapters ?? nativeAdapters(); + chosen = adapter ?? nativeAdapter(); } catch (error) { - return Promise.reject( - error instanceof DeviceMobileKeyError - ? error - : new DeviceMobileKeyError( - 'ENTROPY_UNAVAILABLE', - 'Native Mobile Key services are unavailable' - ) - ); + return Promise.reject(error); } - const task = loadOrCreate(service, chosenAdapters); - inFlight.set(service, task); + let nativeSeed: Promise; + try { + nativeSeed = chosen.getOrCreateSeedBase64(); + } catch (error) { + return Promise.reject(error); + } + const task = nativeSeed.then((base64) => { + const seed = decodeNativeSeed(base64); + try { + return deriveDeviceMobileKeyPublic(seed); + } finally { + seed.fill(0); + } + }); + inFlight.set(bundleId, task); const clear = () => { - if (inFlight.get(service) === task) inFlight.delete(service); + if (inFlight.get(bundleId) === task) inFlight.delete(bundleId); }; void task.then(clear, clear); return task; diff --git a/src/services/wallets/recoverable/hardwarePublicImport.ts b/src/services/wallets/recoverable/hardwarePublicImport.ts new file mode 100644 index 000000000..ccf29ad02 --- /dev/null +++ b/src/services/wallets/recoverable/hardwarePublicImport.ts @@ -0,0 +1,176 @@ +import { SignerType } from '../enums'; +import { + HardwareTransport, + RecoverableHardwareSigner, + RecoverablePolicyDraftError, + validateRecoverableHardwareSigner, +} from './policyDraft'; + +/** Parsed public exports only. This module never opens a device or creates a wallet. */ +export interface RecoverableHardwarePublicImportInput { + device: SignerType.COLDCARD | SignerType.JADE; + transport: HardwareTransport; + payload: unknown; + /** Caller-assigned public reference to this import, never a secret. */ + sourceId: string; +} + +export interface RecoverableHardwarePublicImport { + kind: 'public-hardware-import'; + signer: RecoverableHardwareSigner; + /** Parsing an export cannot prove possession, connectivity, or policy support. */ + deviceVerification: 'not-verified'; + policyVerification: 'not-verified'; + fundable: false; +} + +type PublicRecord = Record; + +const PRIVATE_FIELD_NAMES = new Set([ + 'xpriv', + 'xprv', + 'tprv', + 'yprv', + 'zprv', + 'uprv', + 'vprv', + 'seed', + 'seedhex', + 'mnemonic', + 'recoverykey', + 'privatekey', + 'masterprivatekey', + 'wif', +]); +const MAX_EXPORT_NODES = 2048; +const MAX_EXPORT_DEPTH = 16; +const MAX_JSON_LENGTH = 128 * 1024; + +function fail(code: string, message: string): never { + throw new RecoverablePolicyDraftError(code, message); +} + +function asRecord(value: unknown): PublicRecord { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + fail('INVALID_HARDWARE_EXPORT', 'Expected a public hardware export object'); + } + return value as PublicRecord; +} + +function parsePayload(payload: unknown): PublicRecord { + if (typeof payload !== 'string') return asRecord(payload); + if (!payload.trim() || payload.length > MAX_JSON_LENGTH) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware export JSON is empty or too large'); + } + try { + return asRecord(JSON.parse(payload)); + } catch (error) { + if (error instanceof RecoverablePolicyDraftError) throw error; + fail('INVALID_HARDWARE_EXPORT', 'Hardware export must be valid JSON'); + } +} + +function assertPublicPayload(payload: PublicRecord): void { + const seen = new Set(); + const pending: { value: unknown; depth: number }[] = [{ value: payload, depth: 0 }]; + let nodes = 0; + while (pending.length) { + const { value, depth } = pending.pop()!; + if (++nodes > MAX_EXPORT_NODES || depth > MAX_EXPORT_DEPTH) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware export is too large or deeply nested'); + } + if (!value || typeof value !== 'object') continue; + if (seen.has(value)) fail('INVALID_HARDWARE_EXPORT', 'Hardware export must be acyclic'); + seen.add(value); + for (const [key, child] of Object.entries(value)) { + const field = key.toLowerCase().replace(/[^a-z0-9]/g, ''); + if (PRIVATE_FIELD_NAMES.has(field)) { + fail('PRIVATE_MATERIAL', 'Hardware export must contain public data only'); + } + pending.push({ value: child, depth: depth + 1 }); + } + } +} + +function assertTestnetDeclaration(record: PublicRecord): void { + for (const field of ['chain', 'network']) { + if (!Object.prototype.hasOwnProperty.call(record, field)) continue; + const value = record[field]; + if ( + typeof value !== 'string' || + !['XTN', 'TESTNET', 'TESTNET3', 'TESTNET4'].includes(value.toUpperCase()) + ) { + fail('TESTNET_ONLY', 'Hardware export declares a non-testnet network'); + } + } +} + +function publicFields( + input: RecoverableHardwarePublicImportInput, + payload: PublicRecord +): Pick { + if (input.device === SignerType.COLDCARD) { + const bip48 = asRecord(payload.bip48_2); + assertTestnetDeclaration(bip48); + return { + xpub: bip48.xpub as string, + derivationPath: bip48.deriv as string, + masterFingerprint: payload.xfp as string, + }; + } + if (input.device === SignerType.JADE) { + const hasBip48Map = Object.prototype.hasOwnProperty.call(payload, '48'); + if ( + hasBip48Map && + ['xPub', 'derivationPath', 'mfp'].some((field) => + Object.prototype.hasOwnProperty.call(payload, field) + ) + ) { + fail('INVALID_HARDWARE_EXPORT', 'Jade export has ambiguous BIP48 public data'); + } + const bip48 = hasBip48Map ? asRecord(payload['48']) : payload; + assertTestnetDeclaration(bip48); + return { + xpub: bip48.xPub as string, + derivationPath: bip48.derivationPath as string, + masterFingerprint: bip48.mfp as string, + }; + } + fail('UNSUPPORTED_HARDWARE', 'Only Coldcard and Jade public imports are supported'); +} + +/** Normalize the known Coldcard/Jade BIP48 export shapes for testnet policy review. */ +export function importRecoverableHardwarePublicData( + input: RecoverableHardwarePublicImportInput +): RecoverableHardwarePublicImport { + if (!input || typeof input !== 'object' || Array.isArray(input)) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware import requires explicit device and source'); + } + for (const field of Object.keys(input)) { + if (!['device', 'transport', 'payload', 'sourceId'].includes(field)) { + fail('UNEXPECTED_FIELD', 'Hardware import has an unexpected field'); + } + } + const payload = parsePayload(input.payload); + assertPublicPayload(payload); + assertTestnetDeclaration(payload); + const fields = publicFields(input, payload); + const signer = validateRecoverableHardwareSigner({ + role: 'hardware', + signerType: input.device, + ...fields, + origin: { + kind: 'hardware-device', + device: input.device, + transport: input.transport, + sourceId: input.sourceId, + }, + }); + return { + kind: 'public-hardware-import', + signer, + deviceVerification: 'not-verified', + policyVerification: 'not-verified', + fundable: false, + }; +} diff --git a/src/services/wallets/recoverable/policyDraft.ts b/src/services/wallets/recoverable/policyDraft.ts index b5ebe6f31..d138e6225 100644 --- a/src/services/wallets/recoverable/policyDraft.ts +++ b/src/services/wallets/recoverable/policyDraft.ts @@ -265,7 +265,10 @@ function validateMobile(signer: RecoverableMobileSigner): RecoverableMobileSigne }; } -function validateHardware(signer: RecoverableHardwareSigner): RecoverableHardwareSigner { +/** Validate public hardware metadata only; this does not establish device possession or policy support. */ +export function validateRecoverableHardwareSigner( + signer: RecoverableHardwareSigner +): RecoverableHardwareSigner { const normalized = normalizePublicSigner(signer, 'hardware'); if (normalized.origin && typeof normalized.origin === 'object') { assertOnlyKeys( @@ -473,7 +476,7 @@ export function buildRecoverablePolicyReview( fail('TESTNET_ONLY', 'Recoverable Wallet policy drafts are testnet-only'); } const mobile = validateMobile(input.mobile); - const hardware = validateHardware(input.hardware); + const hardware = validateRecoverableHardwareSigner(input.hardware); const server = validateServer(input.server); const inheritance = input.inheritance ? validateInheritance(input.inheritance) : null; assertDistinctSigners([mobile, hardware, server, ...(inheritance ? [inheritance.signer] : [])]); diff --git a/tests/services/recoverable/deviceMobileKey.test.ts b/tests/services/recoverable/deviceMobileKey.test.ts index 62f77d4be..295e69995 100644 --- a/tests/services/recoverable/deviceMobileKey.test.ts +++ b/tests/services/recoverable/deviceMobileKey.test.ts @@ -15,36 +15,22 @@ jest.mock('react-native-device-info', () => ({ default: { getBundleId: jest.fn(() => 'io.hexawallet.keeper.recoverablepreview') }, })); -const previewBundleId = 'io.hexawallet.keeper.recoverablepreview'; -const service = `${previewBundleId}.mobile-key.v1`; const seed = Buffer.from('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', 'hex'); +const androidPreviewId = 'io.hexawallet.keeper.recoverablepreview'; +const iosPreviewId = 'io.hexawallet.hexakeeper.recoverablepreview'; -type Stored = false | { service: string; username: string; password: string; storage?: string }; - -function fixture(platform: DeviceMobileKeyAdapters['platform'] = 'ios') { - let stored: Stored = false; - const adapters: DeviceMobileKeyAdapters = { - platform, - entropy: { getRandomBase64: jest.fn(() => seed.toString('base64')) }, - keychain: { - getGenericPassword: jest.fn(async () => stored), - setGenericPassword: jest.fn(async (username, password, options) => { - stored = { service: options.service, username, password, storage: options.storage }; - return { service: options.service, storage: options.storage }; - }), - }, - }; - return { adapters, getStored: () => stored, setStored: (value: Stored) => (stored = value) }; +function adapter(value = seed.toString('base64')): DeviceMobileKeyAdapters { + return { getOrCreateSeedBase64: jest.fn(async () => value) }; } describe('preview device-generated Mobile Key', () => { beforeEach(() => { NativeConfig.KEEPER_PREVIEW = 'true'; NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY = 'true'; - (DeviceInfo.getBundleId as jest.Mock).mockReturnValue(previewBundleId); + (DeviceInfo.getBundleId as jest.Mock).mockReset().mockReturnValue(androidPreviewId); }); - it('derives a stable testnet BIP48 account tpub and exposes no seed', () => { + it('derives a stable testnet BIP48 public signer without returning the seed', () => { const signer = deriveDeviceMobileKeyPublic(seed); expect(signer).toMatchObject({ role: 'mobile', @@ -55,218 +41,107 @@ describe('preview device-generated Mobile Key', () => { expect(signer.xpub).toBe( 'tpubDEhFJsryccF9b2PaR3mgUBVfoYbpVaXsmpK6sonC8cysYcpJzYsZfiwkR9JaoiNWCT9o1HN2bFccb2wMnAXGdKpW6nYQukZMZXfF32RnS6y' ); - if (signer.origin.kind !== 'device-generated') throw new Error('Unexpected Mobile Key origin'); - expect(signer.origin.sourceId).toBe(`device-generated:${signer.xpub}`); expect(JSON.stringify(signer)).not.toContain(seed.toString('hex')); - expect(Object.keys(signer)).toEqual([ - 'role', - 'signerType', - 'masterFingerprint', - 'xpub', - 'derivationPath', - 'origin', - ]); }); it.each([Buffer.alloc(0), Buffer.alloc(16), Buffer.alloc(64)])( 'rejects seeds other than 32 bytes', - (invalid) => { - expect(() => deriveDeviceMobileKeyPublic(invalid)).toThrow('32 bytes'); - } + (invalid) => expect(() => deriveDeviceMobileKeyPublic(invalid)).toThrow('32 bytes') ); it.each([ - { previewFlag: undefined, bundleId: previewBundleId, testnetOnlyFlag: 'true' }, - { previewFlag: 'true', bundleId: 'io.hexawallet.keeper', testnetOnlyFlag: 'true' }, - { previewFlag: 'true', bundleId: previewBundleId, testnetOnlyFlag: undefined }, - ])( - 'rejects any non-preview installed identity before touching adapters', - async (wrongRuntime) => { - NativeConfig.KEEPER_PREVIEW = wrongRuntime.previewFlag; - NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY = wrongRuntime.testnetOnlyFlag; - (DeviceInfo.getBundleId as jest.Mock).mockReturnValue(wrongRuntime.bundleId); - const { adapters } = fixture(); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'PREVIEW_ONLY', - }); - expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); - expect(adapters.keychain.getGenericPassword).not.toHaveBeenCalled(); - } - ); - - it('fails closed if native package identity cannot be read', async () => { - (DeviceInfo.getBundleId as jest.Mock).mockImplementationOnce(() => { - throw new Error('native identity unavailable'); - }); - const { adapters } = fixture(); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ + { bundleId: 'io.hexawallet.keeper', preview: 'true', testnet: 'true' }, + { bundleId: androidPreviewId, preview: undefined, testnet: 'true' }, + { bundleId: androidPreviewId, preview: 'true', testnet: undefined }, + ])('rejects non-preview installed identity before native key access', async (runtime) => { + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue(runtime.bundleId); + NativeConfig.KEEPER_PREVIEW = runtime.preview; + NativeConfig.KEEPER_PREVIEW_TESTNET_ONLY = runtime.testnet; + const native = adapter(); + await expect(getOrCreatePreviewDeviceMobileKey(native)).rejects.toMatchObject({ code: 'PREVIEW_ONLY', }); - expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); - expect(adapters.keychain.getGenericPassword).not.toHaveBeenCalled(); + expect(native.getOrCreateSeedBase64).not.toHaveBeenCalled(); }); - it('stores once under the exact preview service, reads back, and returns public details only', async () => { - const { adapters, getStored } = fixture(); - const result = await getOrCreatePreviewDeviceMobileKey(adapters); - expect(result.xpub).toMatch(/^tpub/); - expect(JSON.stringify(result)).not.toContain(seed.toString('hex')); - expect(adapters.entropy.getRandomBase64).toHaveBeenCalledWith(32); - expect(adapters.keychain.getGenericPassword).toHaveBeenCalledWith({ - service, - cloudSync: false, - }); - expect(adapters.keychain.setGenericPassword).toHaveBeenCalledWith( - 'recoverable-mobile-key-v1', - expect.any(String), - { - service, - accessible: 'AccessibleWhenUnlockedThisDeviceOnly', - cloudSync: false, - } - ); - expect(JSON.parse((getStored() as Exclude).password)).toMatchObject({ - version: 1, - network: 'testnet', - signerPath: "m/48'/1'/0'/2'", - seedHex: seed.toString('hex'), - xpub: result.xpub, - }); - expect(await getOrCreatePreviewDeviceMobileKey(adapters)).toEqual(result); - expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); - expect(adapters.entropy.getRandomBase64).toHaveBeenCalledTimes(1); - }); - - it('requires Android Keystore-backed software security and AES-GCM storage', async () => { - const { adapters, getStored, setStored } = fixture('android'); - await getOrCreatePreviewDeviceMobileKey(adapters); - expect(adapters.keychain.setGenericPassword).toHaveBeenCalledWith( - 'recoverable-mobile-key-v1', - expect.any(String), - { - service, - accessible: 'AccessibleWhenUnlockedThisDeviceOnly', - cloudSync: false, - securityLevel: 'SECURE_SOFTWARE', - storage: 'KeystoreAESGCM_NoAuth', - } - ); - const stored = getStored() as Exclude; - setStored({ ...stored, storage: 'KeystoreAESCBC' }); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'INVALID_STORAGE', - }); - expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); - }); - - it('never generates or overwrites a corrupt existing record', async () => { - const { adapters, setStored } = fixture(); - setStored({ service, username: 'recoverable-mobile-key-v1', password: '{' }); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'INVALID_STORAGE', + it('fails closed when installed package identity cannot be read', async () => { + (DeviceInfo.getBundleId as jest.Mock).mockImplementation(() => { + throw new Error('native identity unavailable'); }); - expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); - expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); - }); - - it('does not replace a stored key whose public data disagrees with the seed', async () => { - const { adapters, getStored, setStored } = fixture(); - await getOrCreatePreviewDeviceMobileKey(adapters); - const existing = getStored() as Exclude; - const record = JSON.parse(existing.password); - record.xpub = 'tpubcorrupted'; - setStored({ ...existing, password: JSON.stringify(record) }); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'INVALID_STORAGE', + const native = adapter(); + await expect(getOrCreatePreviewDeviceMobileKey(native)).rejects.toMatchObject({ + code: 'PREVIEW_ONLY', }); - expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); - expect(adapters.entropy.getRandomBase64).toHaveBeenCalledTimes(1); + expect(native.getOrCreateSeedBase64).not.toHaveBeenCalled(); }); - it('does not generate when the keychain read throws', async () => { - const { adapters } = fixture(); - adapters.keychain.getGenericPassword = jest.fn(async () => { - throw new Error('locked'); + it('fails closed without the preview native key module', async () => { + await expect(getOrCreatePreviewDeviceMobileKey()).rejects.toMatchObject({ + code: 'NATIVE_KEY_UNAVAILABLE', }); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toThrow('locked'); - expect(adapters.entropy.getRandomBase64).not.toHaveBeenCalled(); - expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); }); - it('fails closed when the native entropy call fails or returns malformed data', async () => { - const { adapters } = fixture(); - adapters.entropy.getRandomBase64 = jest.fn(() => { - throw new Error('native unavailable'); - }); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toThrow('native unavailable'); - expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); - - adapters.entropy.getRandomBase64 = jest.fn(() => 'not base64'); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'INVALID_ENTROPY', - }); - expect(adapters.keychain.setGenericPassword).not.toHaveBeenCalled(); - }); + it.each([androidPreviewId, iosPreviewId])( + 'accepts an exact preview app identity: %s', + async (bundleId) => { + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue(bundleId); + const native = adapter(); + const signer = await getOrCreatePreviewDeviceMobileKey(native); + expect(native.getOrCreateSeedBase64).toHaveBeenCalledTimes(1); + expect(signer.xpub).toMatch(/^tpub/); + expect(JSON.stringify(signer)).not.toContain(seed.toString('hex')); + expect(Object.keys(signer)).toEqual([ + 'role', + 'signerType', + 'masterFingerprint', + 'xpub', + 'derivationPath', + 'origin', + ]); + } + ); - it('does not report success on failed write or failed readback', async () => { - const { adapters } = fixture(); - adapters.keychain.setGenericPassword = jest.fn(async () => false); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'WRITE_FAILED', - }); + it.each(['not base64', Buffer.alloc(16).toString('base64'), ''])( + 'rejects malformed native seed output', + async (value) => { + await expect(getOrCreatePreviewDeviceMobileKey(adapter(value))).rejects.toMatchObject({ + code: 'INVALID_NATIVE_SEED', + }); + } + ); - let reads = 0; - adapters.keychain.getGenericPassword = jest.fn(async () => { - reads += 1; - return false; - }); - adapters.keychain.setGenericPassword = jest.fn(async () => ({ service })); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'READBACK_FAILED', - }); - expect(reads).toBe(2); + it('propagates native storage failure instead of reporting a ready key', async () => { + const native: DeviceMobileKeyAdapters = { + getOrCreateSeedBase64: jest.fn(async () => { + throw new Error('secure storage unavailable'); + }), + }; + await expect(getOrCreatePreviewDeviceMobileKey(native)).rejects.toThrow( + 'secure storage unavailable' + ); }); - it('rejects a different key returned by secure-storage readback', async () => { - const { adapters } = fixture(); - let reads = 0; - adapters.keychain.getGenericPassword = jest.fn(async () => { - reads += 1; - return reads === 1 - ? false - : { - service, - username: 'recoverable-mobile-key-v1', - password: JSON.stringify({ - version: 1, - network: 'testnet', - signerPath: "m/48'/1'/0'/2'", - seedHex: Buffer.alloc(32, 1).toString('hex'), - masterFingerprint: deriveDeviceMobileKeyPublic(Buffer.alloc(32, 1)).masterFingerprint, - xpub: deriveDeviceMobileKeyPublic(Buffer.alloc(32, 1)).xpub, - }), - }; - }); - await expect(getOrCreatePreviewDeviceMobileKey(adapters)).rejects.toMatchObject({ - code: 'READBACK_MISMATCH', - }); + it('propagates a synchronous native bridge failure instead of reporting a ready key', async () => { + const native: DeviceMobileKeyAdapters = { + getOrCreateSeedBase64: jest.fn(() => { + throw new Error('native bridge unavailable'); + }), + }; + await expect(getOrCreatePreviewDeviceMobileKey(native)).rejects.toThrow( + 'native bridge unavailable' + ); }); - it('shares one in-process creation across concurrent callers', async () => { - const { adapters, getStored } = fixture(); - let releaseRead: (value: Stored) => void = () => undefined; - adapters.keychain.getGenericPassword = jest - .fn() - .mockImplementationOnce(() => new Promise((resolve) => (releaseRead = resolve))) - .mockImplementation(async () => getStored()); - - const first = getOrCreatePreviewDeviceMobileKey(adapters); - const second = getOrCreatePreviewDeviceMobileKey(adapters); + it('shares one in-process native request across concurrent callers', async () => { + let release: (value: string) => void = () => undefined; + const native: DeviceMobileKeyAdapters = { + getOrCreateSeedBase64: jest.fn(() => new Promise((resolve) => (release = resolve))), + }; + const first = getOrCreatePreviewDeviceMobileKey(native); + const second = getOrCreatePreviewDeviceMobileKey(native); expect(first).toBe(second); - expect(adapters.keychain.getGenericPassword).toHaveBeenCalledTimes(1); - releaseRead(false); + expect(native.getOrCreateSeedBase64).toHaveBeenCalledTimes(1); + release(seed.toString('base64')); expect(await first).toEqual(await second); - expect(adapters.entropy.getRandomBase64).toHaveBeenCalledTimes(1); - expect(adapters.keychain.setGenericPassword).toHaveBeenCalledTimes(1); }); }); diff --git a/tests/services/recoverable/hardwarePublicImport.test.ts b/tests/services/recoverable/hardwarePublicImport.test.ts new file mode 100644 index 000000000..abd5378b4 --- /dev/null +++ b/tests/services/recoverable/hardwarePublicImport.test.ts @@ -0,0 +1,282 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import { SignerType } from 'src/services/wallets/enums'; +import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; +import { RecoverablePolicyDraftError } from 'src/services/wallets/recoverable/policyDraft'; +import { + importRecoverableHardwarePublicData, + RecoverableHardwarePublicImportInput, +} from 'src/services/wallets/recoverable/hardwarePublicImport'; + +const bip32 = BIP32Factory(ecc); +const path = "m/48'/1'/0'/2'"; +const root = bip32.fromSeed(Buffer.alloc(32, 17), bitcoin.networks.testnet); +const tpub = root.derivePath(path).neutered().toBase58(); +const fingerprint = root.fingerprint.toString('hex').toUpperCase(); + +function coldcard( + overrides: Partial = {} +): RecoverableHardwarePublicImportInput { + return { + device: SignerType.COLDCARD, + transport: 'file' as const, + sourceId: 'coldcard-public-export-1', + payload: { + chain: 'XTN', + xfp: fingerprint.toLowerCase(), + bip48_2: { deriv: path, xpub: tpub }, + bip84: { deriv: "m/84'/1'/0'", xpub: 'unused-public-single-key' }, + }, + ...overrides, + }; +} + +function jade( + overrides: Partial = {} +): RecoverableHardwarePublicImportInput { + return { + device: SignerType.JADE, + transport: 'qr' as const, + sourceId: 'jade-public-qr-1', + payload: { + network: 'testnet', + 48: { xPub: tpub, derivationPath: path, mfp: fingerprint.toLowerCase() }, + 84: { xPub: 'unused-public-single-key', derivationPath: "m/84'/1'/0'" }, + }, + ...overrides, + }; +} + +function expectCode(action: () => unknown, code: string) { + try { + action(); + throw new Error(`Expected ${code}`); + } catch (error) { + expect(error).toBeInstanceOf(RecoverablePolicyDraftError); + expect((error as RecoverablePolicyDraftError).code).toBe(code); + } +} + +describe('testnet public hardware import', () => { + test('normalizes a Coldcard BIP48 export without carrying unrelated export fields', () => { + const result = importRecoverableHardwarePublicData(coldcard()); + expect(result).toEqual({ + kind: 'public-hardware-import', + signer: { + role: 'hardware', + signerType: SignerType.COLDCARD, + masterFingerprint: fingerprint, + xpub: tpub, + derivationPath: path, + origin: { + kind: 'hardware-device', + device: SignerType.COLDCARD, + transport: 'file', + sourceId: 'coldcard-public-export-1', + }, + }, + deviceVerification: 'not-verified', + policyVerification: 'not-verified', + fundable: false, + }); + expect(JSON.stringify(result)).not.toContain('bip84'); + }); + + test('accepts the mapped Jade QR shape and a direct BIP48 Jade object', () => { + const mapped = importRecoverableHardwarePublicData(jade()); + expect(mapped.signer).toMatchObject({ + signerType: SignerType.JADE, + masterFingerprint: fingerprint, + xpub: tpub, + derivationPath: path, + origin: { transport: 'qr', sourceId: 'jade-public-qr-1' }, + }); + expect(mapped.deviceVerification).toBe('not-verified'); + + const direct = importRecoverableHardwarePublicData( + jade({ + transport: 'desktop-usb', + payload: { xPub: tpub, derivationPath: path, mfp: fingerprint }, + }) + ); + expect(direct.signer.origin.transport).toBe('desktop-usb'); + expect(direct.policyVerification).toBe('not-verified'); + }); + + test('accepts a JSON file as input and keeps its status unverified', () => { + const input = coldcard(); + const result = importRecoverableHardwarePublicData({ + ...input, + payload: JSON.stringify(input.payload), + }); + expect(result.signer.xpub).toBe(tpub); + expect(result.fundable).toBe(false); + }); + + test('accepts an explicit nonzero testnet BIP48 account', () => { + const accountPath = "m/48'/1'/7'/2'"; + const accountTpub = root.derivePath(accountPath).neutered().toBase58(); + const result = importRecoverableHardwarePublicData( + coldcard({ + payload: { + xfp: fingerprint, + bip48_2: { deriv: accountPath, xpub: accountTpub }, + }, + }) + ); + expect(result.signer.derivationPath).toBe(accountPath); + expect(result.signer.xpub).toBe(accountTpub); + }); + + test('rejects mainnet paths, extended keys, and declared mainnet exports', () => { + const mainnetRoot = bip32.fromSeed(Buffer.alloc(32, 18), bitcoin.networks.bitcoin); + const mainnetXpub = mainnetRoot.derivePath("m/48'/0'/0'/2'").neutered().toBase58(); + expectCode( + () => + importRecoverableHardwarePublicData( + coldcard({ + payload: { xfp: fingerprint, bip48_2: { deriv: "m/48'/0'/0'/2'", xpub: tpub } }, + }) + ), + 'INVALID_DERIVATION' + ); + expectCode( + () => + importRecoverableHardwarePublicData( + jade({ payload: { xPub: mainnetXpub, derivationPath: path, mfp: fingerprint } }) + ), + 'INVALID_XPUB' + ); + expectCode( + () => + importRecoverableHardwarePublicData( + coldcard({ + payload: { chain: 'BTC', xfp: fingerprint, bip48_2: { deriv: path, xpub: tpub } }, + }) + ), + 'TESTNET_ONLY' + ); + }); + + test('rejects wrong BIP48 script branch and non-account extended keys', () => { + expectCode( + () => + importRecoverableHardwarePublicData( + jade({ payload: { xPub: tpub, derivationPath: "m/48'/1'/0'/1'", mfp: fingerprint } }) + ), + 'INVALID_DERIVATION' + ); + expectCode( + () => + importRecoverableHardwarePublicData( + jade({ + payload: { xPub: root.neutered().toBase58(), derivationPath: path, mfp: fingerprint }, + }) + ), + 'INVALID_XPUB_ORIGIN' + ); + }); + + test('rejects private material even in otherwise valid public exports', () => { + expectCode( + () => + importRecoverableHardwarePublicData( + coldcard({ + payload: { + xfp: fingerprint, + bip48_2: { deriv: path, xpub: tpub, xprv: 'private-value' }, + }, + }) + ), + 'PRIVATE_MATERIAL' + ); + expectCode( + () => + importRecoverableHardwarePublicData( + jade({ + payload: { 48: { xPub: tpub, derivationPath: path, mfp: fingerprint }, seed: 'secret' }, + }) + ), + 'PRIVATE_MATERIAL' + ); + expectCode( + () => + importRecoverableHardwarePublicData( + jade({ + payload: { + xPub: root.derivePath(path).toBase58(), + derivationPath: path, + mfp: fingerprint, + }, + }) + ), + 'PRIVATE_MATERIAL' + ); + }); + + test('rejects unsupported hardware/transport, ambiguous Jade data and missing source', () => { + expectCode( + () => importRecoverableHardwarePublicData(jade({ transport: 'nfc' })), + 'UNSUPPORTED_HARDWARE' + ); + expectCode( + () => importRecoverableHardwarePublicData(jade({ device: SignerType.TAPSIGNER as any })), + 'UNSUPPORTED_HARDWARE' + ); + expectCode( + () => + importRecoverableHardwarePublicData( + jade({ + payload: { + 48: { xPub: tpub, derivationPath: path, mfp: fingerprint }, + xPub: tpub, + }, + }) + ), + 'INVALID_HARDWARE_EXPORT' + ); + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ sourceId: '' })), + 'INVALID_ORIGIN' + ); + }); + + test('rejects malformed or missing public material', () => { + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload: '{broken' })), + 'INVALID_HARDWARE_EXPORT' + ); + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload: { xfp: fingerprint } })), + 'INVALID_HARDWARE_EXPORT' + ); + expectCode( + () => + importRecoverableHardwarePublicData(jade({ payload: { xPub: tpub, mfp: fingerprint } })), + 'INVALID_DERIVATION' + ); + expectCode( + () => + importRecoverableHardwarePublicData( + coldcard({ payload: { xfp: 'bad', bip48_2: { deriv: path, xpub: tpub } } }) + ), + 'INVALID_FINGERPRINT' + ); + }); + + test('rejects oversized object exports before parsing public fields', () => { + expectCode( + () => + importRecoverableHardwarePublicData( + coldcard({ + payload: { + xfp: fingerprint, + bip48_2: { deriv: path, xpub: tpub }, + padding: Array(2050).fill('unused'), + }, + }) + ), + 'INVALID_HARDWARE_EXPORT' + ); + }); +}); From 2999a75c1ccfc6ff1436f29d75227ab67c62e8d6 Mon Sep 17 00:00:00 2001 From: Anant Date: Fri, 9 Oct 2026 17:40:30 +0530 Subject: [PATCH 12/31] Clarify testnet rollout and real inheritance recovery checks --- docs/preview/recoverable-wallet/README.md | 1 + docs/preview/recoverable-wallet/policy-draft.md | 2 ++ docs/preview/recoverable-wallet/recovery-contact.md | 2 ++ 3 files changed, 5 insertions(+) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index b82ba5119..62eac50d8 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -76,6 +76,7 @@ Each checkpoint may be smaller than the grouping above to keep visible feedback ## Integration and communications +- The first live Seedless Wallet trial belongs in Keeper's existing **Testnet** mode: show the choice only while Testnet is active, and keep Mainnet hidden until a separate release decision. The separately installed Keeper Preview remains the engineering walkthrough. Enabling the normal-app choice requires a reviewed testnet-scoped key/backup namespace and create, sign, and restore guards; the current Preview identity gate is not a user rollout switch. - Stay rebased on the current Keeper app branch; keep product-facing changes isolated behind a guarded preview feature path. Nothing is merged into shipping app without reviewed CI/native regression and owner approval. - Server code is **frozen for this feature pending Adam's contribution and a new owner instruction**. The absence of Adam's PR does not block preview UI, local hardware functionality, cloud transport tests, threat modeling or design. - Keep existing R5–R10 commitments intact. This work is recorded in a separate **Now — Parallel Recoverable Wallet** tracker entry, *not* a new numbered work bucket. Release integration will be scheduled later on evidence of readiness. diff --git a/docs/preview/recoverable-wallet/policy-draft.md b/docs/preview/recoverable-wallet/policy-draft.md index f3ab2b5af..d6bdc0978 100644 --- a/docs/preview/recoverable-wallet/policy-draft.md +++ b/docs/preview/recoverable-wallet/policy-draft.md @@ -10,4 +10,6 @@ Without Inheritance Key, the review contains Keeper's plain 2-of-3 `VaultScheme` Inheritance activation is an explicit absolute block height or median-time-past value supplied with a chain observation; this module does not choose a default duration or query the chain. The product decision on fixed versus renewed timing is pending. Keeper's existing testnet duration labels are accelerated, so no UI should present a testnet “1 year” setting as a literal year. An absolute delayed path never resets from app activity. Changing that policy later requires migration and an on-chain transfer. +Exercise the time-dependent flow in three distinct ways: a visibly simulated before/after walkthrough for UX, a disposable public-testnet wallet with a short lock labeled in actual blocks and a real pre-maturity failure/post-maturity spend, and a private regtest chain for fast automated block advancement. Never let a changed phone clock or simulation state unlock a real wallet. Before final policy approval the user can cancel or change the choice; after funding, revoking or extending an inheritance path requires a new policy and a complete on-chain sweep, followed by monitoring of the old addresses. + Focused tests cover testnet-only inputs, public-key origin shape, duplicate rejection, optional delayed script/witness combinations, blocked hardware combinations, future locktime, and the non-fundable result. Actual receive/send, physical signer compatibility, descriptor import into another wallet, chain maturity, and server-independent heir exit still require separate tests and review. diff --git a/docs/preview/recoverable-wallet/recovery-contact.md b/docs/preview/recoverable-wallet/recovery-contact.md index 399224bba..cede44911 100644 --- a/docs/preview/recoverable-wallet/recovery-contact.md +++ b/docs/preview/recoverable-wallet/recovery-contact.md @@ -12,6 +12,8 @@ An eventual client implementation should generate a fresh random backup encrypti On a replacement phone, the client should download the encrypted blob, create an ephemeral replacement-device public key and one-time request, then exchange the request and response directly with the contact by QR or an external share channel. The contact must identify the person asking through a separate, human-verifiable check before approval. A reviewed encryption implementation must bind the contact's response to the wallet, request nonce, expiry, enrolled credential, and replacement-device key. The request and response must work while Keeper SigningServer and Relay are unreachable. A contact approval is not itself a decrypted backup or restored key. +For the first live testnet trial, the replacement is the same Keeper app installed on a fresh second phone with Testnet selected; no separate consumer app or new wallet is required. A successful same-key restore must match the original Mobile Key public identity, canonical wallet-policy hash, and receive addresses before the UI reports recovery. Never run create-or-load on an empty replacement store and label its newly generated key as recovered. Prove this with a fresh device rather than relying on uninstall/reinstall alone, since local secure-storage persistence can obscure loss of the original phone. + The request and cloud receipt use a 32-byte public `walletPolicyHash`, not Bitcoin's 4-byte master fingerprint. A future implementation must derive this commitment from the **canonical final public policy/descriptor**, persist it with the encrypted backup, and verify it during restore. This state model checks its format and equality only; it cannot prove the hash was derived correctly or that the descriptor is authentic. ## What the state model enforces now From 25b0b5427301c2438b82524456ce5a9adde6097d Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:23:39 +0530 Subject: [PATCH 13/31] copy(preview): rename Seedless Wallet to Assisted Multisig --- src/components/WalletCreationChooser.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/WalletCreationChooser.tsx b/src/components/WalletCreationChooser.tsx index af17749d4..245643ba9 100644 --- a/src/components/WalletCreationChooser.tsx +++ b/src/components/WalletCreationChooser.tsx @@ -146,7 +146,7 @@ export default function WalletCreationChooser({ {showSeedless && onSeedlessWallet && ( <> Date: Sun, 11 Oct 2026 15:23:42 +0530 Subject: [PATCH 14/31] copy(preview): rename Seedless Wallet to Assisted Multisig --- .../recoverable-wallet/RecoverableWalletPreviewApp.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index e7a425615..e86eb7b84 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -324,7 +324,7 @@ function PreviewContent() { : 'TESTNET PREVIEW · Simulated choices. No wallet, key, address, or backup is created.' } seedlessResumeHint={ - hasDraft ? 'Your Seedless Wallet walkthrough will resume where you left off.' : undefined + hasDraft ? 'Your Assisted Multisig walkthrough will resume where you left off.' : undefined } /> ); @@ -353,7 +353,7 @@ function PreviewContent() { ? 'Cloud Backup' : surface === 'contact' ? 'Recovery Contact' - : 'Seedless Wallet' + : 'Assisted Multisig' } onBack={surface === 'wallets' ? undefined : back} palette={palette} From 7cd73a4a121832919622af9cb74faab31ca3e882 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:23:45 +0530 Subject: [PATCH 15/31] copy(preview): rename Seedless Wallet to Assisted Multisig --- src/screens/AddWalletScreen/WalletChoiceScreen.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx index bae49a88f..251cb9e53 100644 --- a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx +++ b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx @@ -60,7 +60,7 @@ export default function WalletChoiceScreen({ route }: { route?: WalletChoiceRout ? 'Hot Wallet' : stage === 'cold' ? 'Cold Wallet' - : 'Seedless Wallet'; + : 'Assisted Multisig'; return ( @@ -73,7 +73,7 @@ export default function WalletChoiceScreen({ route }: { route?: WalletChoiceRout onAdvancedWallet={() => navigation.navigate('AddNewWallet')} onImportWallet={() => navigation.navigate('VaultConfigurationCreation')} showSeedless - previewNotice="TESTNET PREVIEW · Seedless setup is simulated; no Seedless Wallet is created." + previewNotice="TESTNET PREVIEW · Assisted Multisig setup is simulated; no wallet is created." /> )} {stage === 'simple' && ( @@ -119,7 +119,7 @@ export default function WalletChoiceScreen({ route }: { route?: WalletChoiceRout {stage === 'seedless' && ( - The Seedless Wallet walkthrough runs in the separate Keeper Preview app. + The Assisted Multisig walkthrough runs in the separate Keeper Preview app. No Mobile Key, Server Key, hardware connection, or wallet is created from this screen. From aba5c8a7fd226508938536b3b40470d97446e11b Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:23:48 +0530 Subject: [PATCH 16/31] copy(preview): rename Seedless Wallet to Assisted Multisig --- tests/preview/recoverableWalletScreen.test.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index b5ba72d72..f3b985898 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -223,7 +223,7 @@ describe('Recoverable Wallet preview on a small screen', () => { fireEvent.press(screen.getByTestId('primary-Finish Preview')); expect(screen.getByTestId('preview-complete')).toHaveTextContent('No wallet was created'); fireEvent.press(screen.getByTestId('preview-done')); - expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('Seedless Wallet'); + expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('Assisted Multisig'); fireEvent.press(screen.getByTestId('wallet-choice-seedless')); expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent( 'Adding… · SIMULATED' @@ -278,7 +278,7 @@ describe('Recoverable Wallet preview on a small screen', () => { const screen = render(); const chooser = screen.getByTestId('wallet-creation-chooser'); expect(chooser).toHaveTextContent('Single-Key Wallet'); - expect(chooser).toHaveTextContent('Seedless Wallet'); + expect(chooser).toHaveTextContent('Assisted Multisig'); expect(chooser).toHaveTextContent('Custom Wallet'); expect(chooser).toHaveTextContent('Use your phone or a signing device.'); expect(chooser).toHaveTextContent( @@ -290,7 +290,7 @@ describe('Recoverable Wallet preview on a small screen', () => { expect(chooser).not.toHaveTextContent('FEATURED'); expect(chooser).not.toHaveTextContent('SINGLE KEY'); expect(chooser).not.toHaveTextContent('CUSTOM MULTISIG'); - const seedlessTitle = screen.getByText('Seedless Wallet'); + const seedlessTitle = screen.getByText('Assisted Multisig'); expect(seedlessTitle.props.allowFontScaling).toBe(true); expect(seedlessTitle.props.numberOfLines).toBeUndefined(); expect(StyleSheet.flatten(seedlessTitle.props.style).lineHeight).toBeGreaterThan(25); @@ -318,7 +318,7 @@ describe('Recoverable Wallet preview on a small screen', () => { expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('No wallets yet'); }); - test('the shared chooser hides Seedless Wallet unless the caller explicitly enables it', () => { + test('the shared chooser hides Assisted Multisig unless the caller explicitly enables it', () => { const onSeedlessWallet = jest.fn(); const screen = render( From 53abccb6234d1db5f3fde41499d8701f5a53f254 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:23:52 +0530 Subject: [PATCH 17/31] copy(preview): rename Seedless Wallet to Assisted Multisig --- tests/preview/walletChoiceScreen.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/preview/walletChoiceScreen.test.tsx b/tests/preview/walletChoiceScreen.test.tsx index f12533efd..d471040f4 100644 --- a/tests/preview/walletChoiceScreen.test.tsx +++ b/tests/preview/walletChoiceScreen.test.tsx @@ -105,7 +105,7 @@ describe('guarded Wallets chooser route', () => { test('offers guarded choices without opening an unverified Seedless or Simple flow', () => { const screen = render(); - expect(screen.getByTestId('wallet-creation-chooser')).toHaveTextContent('Seedless Wallet'); + expect(screen.getByTestId('wallet-creation-chooser')).toHaveTextContent('Assisted Multisig'); fireEvent.press(screen.getByTestId('wallet-choice-simple')); fireEvent.press(screen.getByTestId('wallet-choice-hot')); expect(screen.getByTestId('wallet-choice-hot-unavailable')).toHaveTextContent( From bb0d625ffec3139f16e846ca08e2ea83c555b1c7 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:24:18 +0530 Subject: [PATCH 18/31] docs(preview): adopt Assisted Multisig chooser name --- docs/preview/recoverable-wallet/README.md | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index 62eac50d8..d9549536d 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -1,10 +1,12 @@ # Recoverable Wallet — parallel Keeper preview -Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Seedless Wallet" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. +**Approved user-facing chooser name (11 October 2026): Assisted Multisig.** Place it between **Single-Key Wallet** and **Custom Wallet**. The former public-facing name is retired. Keep internal `seedless` route IDs, prop names, storage identifiers and testIDs unchanged until a separately reviewed migration; this is a copy/name decision only, not a cryptographic or security guarantee. + +Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Assisted Multisig" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. ## First client checkpoint -- The current package starts at the empty **Wallets** screen with Single-Key, Seedless, and Custom choices; Add Wallet opens the same chooser. Seedless walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. +- The current package starts at the empty **Wallets** screen with Single-Key, Assisted Multisig, and Custom choices; Add Wallet opens the same chooser. Assisted Multisig walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. - TAPSIGNER, Satochip, Jade, and Coldcard appear with their existing Keeper transport choices. The UI says policy verification and full Recoverable Wallet compatibility remain unproven. Every simulated status, error, and completion is labeled. The latest source offers only the base 2-of-3 proposal for TAPSIGNER, Satochip, and Jade; Coldcard alone can proceed to an explicitly unverified Inheritance Key proposal. - The app entry requires the exact preview package ID and testnet-only preview flags. Normal Keeper continues through its original app component. The preview loads no wallet store, cloud backup, signing, or server client. The native preview identifiers are distinct, the Android CloudBackup module is disabled, and the iOS preview has no iCloud entitlement. See [native-preview.md](native-preview.md). - An arm64 Android debug APK with an embedded JavaScript bundle was built and its package identity and debug signature checked. It installed and ran beside both a Keeper development app and the public production Keeper v2.6.3 APK on an Android emulator. Side-by-side installation and storage isolation on physical devices remain unverified. The iOS preview scheme, identifier, plist, and entitlements are configured, but an iOS build has not been run: this checkout lacks matching Pods and has insufficient free disk space for a safe fresh install/build. @@ -22,12 +24,12 @@ The next owner test is to install the Android APK beside normal Keeper, walk thr ## Second client checkpoint in this branch -- The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Single-Key Wallet** (phone or signing device next), prominent **Seedless Wallet**, and **Custom Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. The labels describe setup paths, without a “Featured” badge or a blanket seed-word promise on the card. Single-Key, Custom, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. -- Selecting Seedless immediately starts a compact, simulated progress screen rather than a mandatory introduction: Mobile Key then Server Key status labels advance in order, Hardware Key waits for the user, and **Choose Hardware** enables only after both demo steps. “How it works” is optional in-flow detail; the complete policy remains a required review before any real wallet could be created. The timer changes labels only: it creates no key, backup, server registration, or wallet. A future real “Added” status must wait for verified secure Mobile Key persistence or Server Key registration, respectively; elapsed time cannot establish readiness. -- The default Seedless design calls for an independently generated Mobile Key and no new seed words for the user to record. Derivation from Keeper's existing 12-word Recovery Key remains an **optional creation path**, not a setup prerequisite or chooser message. The isolated BIP85 helper reserves a versioned child range starting at index 1,000,000; Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Seedless. Its pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. A Recovery Key cannot recreate a separately generated Mobile Key by derivation alone; that would require a reviewed encrypted backup or wrapping design. +- The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Single-Key Wallet** (phone or signing device next), prominent **Assisted Multisig**, and **Custom Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. The labels describe setup paths, without a “Featured” badge or a blanket seed-word promise on the card. Single-Key, Custom, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. +- Selecting Assisted Multisig immediately starts a compact, simulated progress screen rather than a mandatory introduction: Mobile Key then Server Key status labels advance in order, Hardware Key waits for the user, and **Choose Hardware** enables only after both demo steps. “How it works” is optional in-flow detail; the complete policy remains a required review before any real wallet could be created. The timer changes labels only: it creates no key, backup, server registration, or wallet. A future real “Added” status must wait for verified secure Mobile Key persistence or Server Key registration, respectively; elapsed time cannot establish readiness. +- The default Assisted Multisig design calls for an independently generated Mobile Key and no new seed words for the user to record. Derivation from Keeper's existing 12-word Recovery Key remains an **optional creation path**, not a setup prerequisite or chooser message. The isolated BIP85 helper reserves a versioned child range starting at index 1,000,000; Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Assisted Multisig. Its pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. A Recovery Key cannot recreate a separately generated Mobile Key by derivation alone; that would require a reviewed encrypted backup or wrapping design. - A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. A separate pure importer accepts public Coldcard/Jade BIP48 testnet exports and marks both the device and policy **not verified**; it does not open a device or connect to the UI. The 2-of-3 and delayed 2-of-4 policy results remain explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). - A client-only Recovery Contact state model covers encrypted-cloud readback receipts, offline retry, invitation/request expiry, approval/decline, and optional recovery-code gating. It stops before cryptographic enrollment or restoration. No contact key, encrypted backup, native cloud container, or independent exchange channel exists yet. See [recovery-contact.md](recovery-contact.md). -- The isolated preview now lets the owner explore Recovery Options after the Seedless walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. +- The isolated preview now lets the owner explore Recovery Options after the Assisted Multisig walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. - Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. The latest client code passed **108 Jest tests across 14 focused suites** covering the direct empty Wallets entry, simulated Mobile/Server failure and retry, Add Wallet chooser, preview isolation, hardware-dependent inheritance gating, Recovery Key education gate, native Mobile Key bridge error handling, public Coldcard/Jade export validation, key-origin policy draft, contact states, and Recovery Key migration. The latest arm64 APK embeds this chooser, shorter copy, simulated setup error/retry states, and Android's preview-only native Mobile Key module. An Android emulator walkthrough at 320dp and 1.6× system font confirmed that the three-choice landing, Mobile/Server statuses, hardware action, persistent setup error sample, and retry remain reachable by scrolling. The complete hardware, inheritance, and final-review walkthrough at that size was recorded against the preceding package; those flow stages did not change in this package. The temporary local Metro symlink adjustment was removed after packaging. @@ -56,7 +58,7 @@ Adam's contribution is welcome, optional, independently reviewed, and must not b - Hardware + Server supports delayed replacement of missing Mobile Key when cloud backup is missing, once server implementation is allowed. - Mobile + Hardware and descriptor support server-independent spending/exit. Test actual external-wallet compatibility; public descriptors do not contain private keys. - Key changes mean new wallet policy and on-chain transfer with fee and original-wallet authorization. Archive the complete predecessor and monitor retained archived addresses indefinitely, including zero-balance wallets. Do not archive merely because the same Mobile Key was restored. -- Keep Recovery Contact distinct from signing keys and Inheritance Key. The existing 12-word Recovery Key is an **additional option**, not a mandatory prerequisite or a message on the Seedless choice. Do not imply it can reproduce an independently generated Mobile Key without an encrypted copy or other reviewed recovery mechanism. +- Keep Recovery Contact distinct from signing keys and Inheritance Key. The existing 12-word Recovery Key is an **additional option**, not a mandatory prerequisite or a message on the Assisted Multisig choice. Do not imply it can reproduce an independently generated Mobile Key without an encrypted copy or other reviewed recovery mechanism. ## How the owner will test it @@ -64,7 +66,7 @@ Deliver a **separate-installation iOS and Android Keeper Preview** (different ap A new preview checkpoint is complete **only after an installable build and a short device-specific owner test checklist are available**, and after actual tests are recorded: -1. **Prototype/UI**: start on empty Wallets or use Add Wallet, choose Seedless Wallet, then review hardware picker/connection, automatic Mobile/Server status, optional inheritance, and one final policy; include errors/cancel/resume. +1. **Prototype/UI**: start on empty Wallets or use Add Wallet, choose Assisted Multisig, then review hardware picker/connection, automatic Mobile/Server status, optional inheritance, and one final policy; include errors/cancel/resume. 2. **Disposable real wallet**: create fixed 2-of-3 wallet on testnet using supported available signers, safely receive/send test sats, inspect proper fees and outputs. No mainnet, no production credentials. 3. **Backup**: encrypted Mobile Key recovery blob, versioning, iCloud/Drive isolation, read-back verification, retry/offline/background/interrupted write tests; retain existing Keeper backup compatibility. 4. **Recovery via hardware**: lose/reinstall disposable preview, prove hardware possession, restore same wallet and explain retain-versus-rotate Mobile Key after restoration. This requires reviewed server protocol; do not simulate as if implemented. @@ -76,7 +78,7 @@ Each checkpoint may be smaller than the grouping above to keep visible feedback ## Integration and communications -- The first live Seedless Wallet trial belongs in Keeper's existing **Testnet** mode: show the choice only while Testnet is active, and keep Mainnet hidden until a separate release decision. The separately installed Keeper Preview remains the engineering walkthrough. Enabling the normal-app choice requires a reviewed testnet-scoped key/backup namespace and create, sign, and restore guards; the current Preview identity gate is not a user rollout switch. +- The first live Assisted Multisig trial belongs in Keeper's existing **Testnet** mode: show the choice only while Testnet is active, and keep Mainnet hidden until a separate release decision. The separately installed Keeper Preview remains the engineering walkthrough. Enabling the normal-app choice requires a reviewed testnet-scoped key/backup namespace and create, sign, and restore guards; the current Preview identity gate is not a user rollout switch. - Stay rebased on the current Keeper app branch; keep product-facing changes isolated behind a guarded preview feature path. Nothing is merged into shipping app without reviewed CI/native regression and owner approval. - Server code is **frozen for this feature pending Adam's contribution and a new owner instruction**. The absence of Adam's PR does not block preview UI, local hardware functionality, cloud transport tests, threat modeling or design. - Keep existing R5–R10 commitments intact. This work is recorded in a separate **Now — Parallel Recoverable Wallet** tracker entry, *not* a new numbered work bucket. Release integration will be scheduled later on evidence of readiness. From 9a545a15f01d8a96eece84969e1c52b05a9ebdfe Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:24:23 +0530 Subject: [PATCH 19/31] docs(preview): adopt Assisted Multisig chooser name --- docs/preview/recoverable-wallet/native-preview.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/preview/recoverable-wallet/native-preview.md b/docs/preview/recoverable-wallet/native-preview.md index 496ff3853..296a672cf 100644 --- a/docs/preview/recoverable-wallet/native-preview.md +++ b/docs/preview/recoverable-wallet/native-preview.md @@ -33,14 +33,14 @@ The local verification worktree shared `node_modules` through a symlink. Metro r The Android package must be installed alongside production Keeper and verified on a device before calling the milestone device-tested. The iOS scheme is configured for the simulator, but a simulator build has not yet completed. A signed physical-device build requires an Apple App ID and provisioning profile for `io.hexawallet.hexakeeper.recoverablepreview`; distribution access must be checked with the Keeper team. Neither cloud backup nor a physical hardware connection is claimed by this milestone. -Local Android emulator verification on 9 October 2026: the current arm64 APK installed and launched from its embedded JavaScript bundle at 320dp width with 1.6× system text. The shorter testnet demo notice leaves the Seedless option visible on the empty Wallets screen; Mobile and Server simulated statuses and Choose Hardware remain reachable by scrolling. The persistent Show Setup Error action, simulated Server Key failure, and Try Again recovery were exercised in the native app. Keeper Preview, an existing development app, and the public production Keeper v2.6.3 APK had distinct package IDs and launched on the same emulator. The preceding package also completed the simulated hardware, connection error, inheritance, review, and completion walkthrough at that size. Physical-device installation and real storage/keychain separation still require checks. +Local Android emulator verification on 9 October 2026: the current arm64 APK installed and launched from its embedded JavaScript bundle at 320dp width with 1.6× system text. The shorter testnet demo notice leaves the Assisted Multisig option visible on the empty Wallets screen; Mobile and Server simulated statuses and Choose Hardware remain reachable by scrolling. The persistent Show Setup Error action, simulated Server Key failure, and Try Again recovery were exercised in the native app. Keeper Preview, an existing development app, and the public production Keeper v2.6.3 APK had distinct package IDs and launched on the same emulator. The preceding package also completed the simulated hardware, connection error, inheritance, review, and completion walkthrough at that size. Physical-device installation and real storage/keychain separation still require checks. Before future cloud backup work, register a dedicated iCloud container for the preview App ID and dedicated Google OAuth/Drive credentials. Keep access disabled until read-back and cross-app isolation are verified on real devices. Do not reuse Keeper's production or development cloud identities. ## Native checks 1. Confirm production Keeper and Keeper Preview install simultaneously without replacing each other. -2. Confirm the preview icon/name is `Keeper Preview`, has no production deep link/backup intent, and starts at the empty Wallets chooser. Selecting Seedless Wallet should start the simulated key sequence directly. +2. Confirm the preview icon/name is `Keeper Preview`, has no production deep link/backup intent, and starts at the empty Wallets chooser. Selecting Assisted Multisig should start the simulated key sequence directly. 3. Check iOS Keychain and Android app data remain inaccessible to the other app. On iOS, inspect the signed preview entitlements; they must contain no production iCloud or Keychain group. 4. Confirm both preview backends use only local unreachable URLs and the UI has no mainnet control, wallet creation, signing, or cloud-backup action. 5. Uninstall Preview and confirm production Keeper and its wallet/backups remain intact. From 9ad607afb934e47956af17235455e0cc2d6188c2 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:24:26 +0530 Subject: [PATCH 20/31] docs(preview): adopt Assisted Multisig chooser name --- docs/preview/recoverable-wallet/policy-draft.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/preview/recoverable-wallet/policy-draft.md b/docs/preview/recoverable-wallet/policy-draft.md index d6bdc0978..a934dbc2f 100644 --- a/docs/preview/recoverable-wallet/policy-draft.md +++ b/docs/preview/recoverable-wallet/policy-draft.md @@ -2,7 +2,7 @@ `src/services/wallets/recoverable/policyDraft.ts` validates a proposed testnet 2-of-3 Mobile Key + Hardware Key + Server Key arrangement using public metadata only. Optional Inheritance Key is included **before** the whole-policy review. The module never requests a key, creates a wallet, registers a policy, signs, or funds an address. Every result is `fundable: false`. -The Mobile Key may have either public origin: `device-generated` (the default Seedless setup path, with an opaque public source reference) or `keeper-recovery-key-bip85` (an optional deterministic recreation path using the version 1 BIP85 reservation outside the existing hot-wallet and USDT ranges). The second origin is valid only when its ordinal, index, and BIP85 path agree. The first origin is **not** deterministically recreatable from Keeper's Recovery Key. Enabling RK-assisted recovery of a device-generated Mobile Key would require a separately designed and verified wrapped-backup protocol; none exists in this draft. The source reference and origin tag cannot prove that native generation, secure storage, or backup occurred. +The Mobile Key may have either public origin: `device-generated` (the default Assisted Multisig setup path, with an opaque public source reference) or `keeper-recovery-key-bip85` (an optional deterministic recreation path using the version 1 BIP85 reservation outside the existing hot-wallet and USDT ranges). The second origin is valid only when its ordinal, index, and BIP85 path agree. The first origin is **not** deterministically recreatable from Keeper's Recovery Key. Enabling RK-assisted recovery of a device-generated Mobile Key would require a separately designed and verified wrapped-backup protocol; none exists in this draft. The source reference and origin tag cannot prove that native generation, secure storage, or backup occurred. All signers need a testnet BIP48 native-segwit account tpub with serialized depth 4 and final hardened child index `2'`. Duplicate fingerprints or tpubs, private fields, mainnet keys, and unsupported import transports are rejected. A tpub **cannot prove** its claimed earlier derivation ancestors, master fingerprint, device identity, or possession; those need device-specific checks before wallet creation. From 2c25a3bbdbaf6d9fecbfd6dd8a53430a87a4ab6e Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:24:30 +0530 Subject: [PATCH 21/31] docs(preview): adopt Assisted Multisig chooser name --- docs/preview/recoverable-wallet/recovery-contact.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/preview/recoverable-wallet/recovery-contact.md b/docs/preview/recoverable-wallet/recovery-contact.md index cede44911..792979df5 100644 --- a/docs/preview/recoverable-wallet/recovery-contact.md +++ b/docs/preview/recoverable-wallet/recovery-contact.md @@ -32,4 +32,4 @@ The request and cloud receipt use a 32-byte public `walletPolicyHash`, not Bitco 4. Build a server-independent QR/share request and response channel with identity checks, approval and decline screens. Confirm the contact cannot silently approve a different wallet or replacement device. 5. Test two devices, both assurance modes, failed cloud readback, expired/replayed messages, lost contact credential, app reinstall, Keeper endpoints blocked, and exact recovered Mobile Key xpub. Obtain independent cryptographic/security review before labeling the path usable. -The default Seedless design uses an independently generated Mobile Key. Keeper's Recovery Key cannot derive that same key; any RK-assisted restoration would need a separately designed encrypted copy or wrapping protocol. If the user explicitly chose the optional RK-derived Mobile Key at creation, that Recovery Key can regenerate the same key without contact approval. Neither route changes the wallet policy by itself. If a key is suspected compromised, rotation still requires a new policy, on-chain transfer, and Archived Wallet handling. +The default Assisted Multisig design uses an independently generated Mobile Key. Keeper's Recovery Key cannot derive that same key; any RK-assisted restoration would need a separately designed encrypted copy or wrapping protocol. If the user explicitly chose the optional RK-derived Mobile Key at creation, that Recovery Key can regenerate the same key without contact approval. Neither route changes the wallet policy by itself. If a key is suspected compromised, rotation still requires a new policy, on-chain transfer, and Archived Wallet handling. From ffbfa8c5628706ca0d174ebdfbe9ef221f7f5181 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:26:35 +0530 Subject: [PATCH 22/31] docs(preview): finalize Assisted Multisig and direct factual Bitkey comparison --- docs/preview/recoverable-wallet/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index d9549536d..b421b60f5 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -2,7 +2,7 @@ **Approved user-facing chooser name (11 October 2026): Assisted Multisig.** Place it between **Single-Key Wallet** and **Custom Wallet**. The former public-facing name is retired. Keep internal `seedless` route IDs, prop names, storage identifiers and testIDs unchanged until a separately reviewed migration; this is a copy/name decision only, not a cryptographic or security guarantee. -Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Assisted Multisig" is the proposed user-facing choice; "Recoverable Wallet" remains the internal working term. +Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Assisted Multisig" is the **approved** user-facing choice; "Recoverable Wallet" remains an internal working term. ## First client checkpoint @@ -82,7 +82,7 @@ Each checkpoint may be smaller than the grouping above to keep visible feedback - Stay rebased on the current Keeper app branch; keep product-facing changes isolated behind a guarded preview feature path. Nothing is merged into shipping app without reviewed CI/native regression and owner approval. - Server code is **frozen for this feature pending Adam's contribution and a new owner instruction**. The absence of Adam's PR does not block preview UI, local hardware functionality, cloud transport tests, threat modeling or design. - Keep existing R5–R10 commitments intact. This work is recorded in a separate **Now — Parallel Recoverable Wallet** tracker entry, *not* a new numbered work bucket. Release integration will be scheduled later on evidence of readiness. -- Prepare, but do not publish, direct factual Bitkey comparison, blog, feature page, demo video, Ask Keeper help, X/Telegram campaign. Emphasize third-party hardware freedom and Miniscript inheritance. Bitkey already publishes source; do not claim otherwise. Keeper owner controls external communications. +- **Directly target people considering Bitkey, by naming Bitkey explicitly** in the comparison blog, search landing page, video and X/Telegram campaign. Do not merely imply a competitor. Proposed blog: “Bitkey vs Bitcoin Keeper: What Changes When You Can Choose Your Own Hardware?” and a “Looking for a Bitkey alternative?” page. Show factual side-by-side differences: third-party hardware choice, Miniscript inheritance, recovery, Server Key trust assumptions, and descriptor-based exit. Challenge products and trade-offs, never attack people or make unsupported claims; Bitkey itself publishes open-source software and supports exit/recovery. Do not brand Keeper as “Open Bitkey” or imply affiliation with Block. **Prepare but do not publish** until functionality and claims are independently tested and owner-approved. Keeper owner controls external communications. - Self-hosted packaging/custom-server settings remain **Later**. No performance/security superiority claims without data. ## Immediate next action From 3b8070339b3466b1d64c320b775a2d5fe707c867 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:57:01 +0530 Subject: [PATCH 23/31] docs(preview): ground campaign and security checks in Ledger and COLDCARD incidents --- docs/preview/recoverable-wallet/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index b421b60f5..8a9e703ba 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -76,6 +76,17 @@ A new preview checkpoint is complete **only after an installable build and a sho Each checkpoint may be smaller than the grouping above to keep visible feedback frequent. Keep a clean recorded matrix of **simulated / automated / native / physical / security-reviewed / user-tested**, never conflating these. +## Hardware-wallet incident lessons: release safety and marketing (11 October 2026) + +Owner instruction: the Assisted Multisig buildup must account for the July 2026 COLDCARD entropy incident and the October 2026 Ledger reseller-tampering reports. This is a durable product and communication rule, not an opportunity to attack affected manufacturers or users. + +- **COLDCARD entropy:** Device firmware versions that generated weak seeds may leave those *existing seeds* exposed even after a firmware update. Migration to a fresh, independently generated signer key and, when necessary, a new wallet policy/on-chain transfer is the relevant remedy, subject to the maker's official advisory. Check actual model, firmware release track, and **when/how the seed was originally generated**, not merely today's firmware version. Do not claim Keeper or multisig can 'fix' an already compromised key. Source: https://coldcard.com/security/status and https://github.com/Coldcard/firmware/blob/master/README.md +- **Ledger incident:** October 2026 reports concern possible supply-chain tampering of devices from a particular reseller; as of this note, ongoing investigation/claims about total losses must be described as **reported/unconfirmed**, not a proven Ledger-wide firmware/secure-element failure. Source: https://www.theverge.com/tech/1009294/ledger-wallet-tampering-suspected-after-reports-of-crypto-thefts and https://www.coindesk.com/business/2026/10/09/ledger-investigates-potential-wallet-tampering-after-reports-of-usd86-million-in-crypto-stolen +- **Threat-model truth:** Standard 2-of-3 means one exposed key alone does not meet the spending threshold, assuming the other two remain independently secure. A compromised device, fake device, malicious coordinator/PSBT, unsafe seed, or combined compromise of Mobile Key + Server Key are still real risks; hardware freedom does not inherently establish device authenticity, entropy strength or signer independence. Our server-assisted recovery trade-off must be disclosed without claiming security superiority. +- **UX and testing acceptance:** Before describing any hardware as "verified"/"safe", check the supported device, exact transport and firmware capabilities, source/provenance, compromised-seed history, policy-aware confirmation vs digest-only signing, and independent transaction/output/change verification where device permits. Document and test warning + optional migration/rotation paths for known affected signer keys, preserving original-wallet signing and archive monitoring. Do not automatically classify device as secure because current firmware is patched; a user-visible unknown status must remain unknown. +- **Public campaign editorial rule:** Name Ledger/COLDCARD only when useful to explain *specific and sourced* failure modes and what users should do, keeping active investigations qualified. Separate impartial incident explainers from Assisted Multisig product promotion. Avoid "Ledger hacked", "COLDCARD broken", "your hardware is no longer trustworthy", "multisig stops hacks", "seedless avoids this", "guaranteed recovery", or incident-driven scare tactics. No unsolicited posts targeted at people reporting losses. Offer practical checks first; discuss the merits and residual risks of independent signers only with qualified, tested claims. +- **Launch proof:** Campaign must not advertise verified signer independence, manufacturer support, secure cloud/contact recovery, protection against hardware compromises, or improved security until real physical/iOS/Android tests and independent review support each specific statement. + ## Integration and communications - The first live Assisted Multisig trial belongs in Keeper's existing **Testnet** mode: show the choice only while Testnet is active, and keep Mainnet hidden until a separate release decision. The separately installed Keeper Preview remains the engineering walkthrough. Enabling the normal-app choice requires a reviewed testnet-scoped key/backup namespace and create, sign, and restore guards; the current Preview identity gate is not a user rollout switch. From b982edffa75d3ba44c2758ac7b643f66e0007a57 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:45:25 +0530 Subject: [PATCH 24/31] testnet(preview): add unfundable 2-of-3 P2WSH script and descriptor vector --- .../recoverable/testnetScriptVector.ts | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/services/wallets/recoverable/testnetScriptVector.ts diff --git a/src/services/wallets/recoverable/testnetScriptVector.ts b/src/services/wallets/recoverable/testnetScriptVector.ts new file mode 100644 index 000000000..c6bac6e50 --- /dev/null +++ b/src/services/wallets/recoverable/testnetScriptVector.ts @@ -0,0 +1,106 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import { Buffer } from 'buffer'; +import { NetworkType } from '../enums'; +import { DescriptorChecksum } from '../operations/descriptors/checksum'; +import ecc from '../operations/taproot-utils/noble_ecc'; +import { + buildRecoverablePolicyReview, + RecoverablePolicyDraftError, + type RecoverablePolicyDraftInput, + type RecoverablePublicSignerBase, +} from './policyDraft'; + +const bip32 = BIP32Factory(ecc); + +/** + * An independent, PUBLIC-ONLY reference for the base 2-of-3 testnet script. + * This is NOT a wallet factory, not proof of hardware possession, not an + * enrolled Server Key, not backup verification and not a receive-address API. + * + * It uses the same sortedmulti/P2WSH construction as Keeper's existing + * DEFAULT_MULTISIG wallet operations. Do not connect this to wallet activation, + * receive UI, chain syncing or real funds. + */ +export interface RecoverableTestnetScriptVector { + kind: 'unfundable-testnet-2-of-3-vector'; + network: NetworkType.TESTNET; + threshold: 2; + signers: 3; + /** Multipath, checksummed, PUBLIC descriptor. No signing secret is present. */ + descriptor: string; + /** Never display for deposits: the server and hardware are not yet verified. */ + referenceAddress: string; + scriptPubKey: Buffer; + witnessScript: Buffer; + internal: boolean; + index: number; + fundable: false; +} + +function keyExpression(signer: RecoverablePublicSignerBase): string { + const origin = signer.derivationPath.slice(2).replace(/'/g, 'h'); + return '[' + signer.masterFingerprint + '/' + origin + ']' + + signer.xpub + '/<0;1>/*'; +} + +/** Deterministic reference script. Every caller remains blocked from funding. */ +export function deriveRecoverableTestnetScriptVector( + input: RecoverablePolicyDraftInput, + internal: boolean, + index: number +): RecoverableTestnetScriptVector { + if (typeof internal !== 'boolean' || + !Number.isSafeInteger(index) || index < 0 || index > 1000) { + throw new RecoverablePolicyDraftError( + 'INVALID_ADDRESS_INDEX', + 'Reference derivation needs a receive/change choice and index 0–1000' + ); + } + + // Validate all origin metadata, network, 2-of-3 threshold, and distinct + // account keys using the existing preview policy validator. + const review = buildRecoverablePolicyReview(input); + if (review.inheritance !== null || review.baseVaultScheme === null) { + throw new RecoverablePolicyDraftError( + 'INHERITANCE_NOT_TESTED', + 'Delayed inheritance needs a separate verified Miniscript script and signer test' + ); + } + const network = bitcoin.networks.testnet; + const signers = review.base.signers; + const pubkeys = signers + .map((signer) => Buffer.from( + bip32.fromBase58(signer.xpub, network) + .derive(internal ? 1 : 0) + .derive(index).publicKey + )) + .sort(Buffer.compare); // BIP67, matching Keeper's default 2-of-3. + + const p2ms = bitcoin.payments.p2ms({ m: 2, pubkeys, network }); + const p2wsh = bitcoin.payments.p2wsh({ redeem: p2ms, network }); + if (!p2ms.output || !p2wsh.output || !p2wsh.address) { + throw new Error('Could not construct a native-segwit 2-of-3 reference script'); + } + + const descriptorBody = 'wsh(sortedmulti(2,' + + signers.map(keyExpression).join(',') + '))'; + const checksum = DescriptorChecksum(descriptorBody); + if (checksum.length !== 8) { + throw new Error('Could not checksum the reference descriptor'); + } + + return { + kind: 'unfundable-testnet-2-of-3-vector', + network: NetworkType.TESTNET, + threshold: 2, + signers: 3, + descriptor: descriptorBody + '#' + checksum, + referenceAddress: p2wsh.address, + scriptPubKey: Buffer.from(p2wsh.output), + witnessScript: Buffer.from(p2ms.output), + internal, + index, + fundable: false, + }; +} From 3c35ebda698be18be836f30c5ba914c991d6f3c0 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:46:24 +0530 Subject: [PATCH 25/31] test(preview): cover BIP67 descriptor compatibility and all 2-of-3 PSBT signer pairs --- .../recoverable/testnetScriptVector.test.ts | 186 ++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 tests/services/recoverable/testnetScriptVector.test.ts diff --git a/tests/services/recoverable/testnetScriptVector.test.ts b/tests/services/recoverable/testnetScriptVector.test.ts new file mode 100644 index 000000000..c7d239606 --- /dev/null +++ b/tests/services/recoverable/testnetScriptVector.test.ts @@ -0,0 +1,186 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import { Buffer } from 'buffer'; +import { NetworkType, SignerType } from 'src/services/wallets/enums'; +import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; +import { + type RecoverablePolicyDraftInput, + RecoverablePolicyDraftError, +} from 'src/services/wallets/recoverable/policyDraft'; +import { deriveRecoverableTestnetScriptVector } from 'src/services/wallets/recoverable/testnetScriptVector'; + +const bip32 = BIP32Factory(ecc); +const PATH = "m/48'/1'/0'/2'"; + +function publicKeyFor(seedByte: number) { + const root = bip32.fromSeed(Buffer.alloc(32, seedByte), bitcoin.networks.testnet); + return { + masterFingerprint: Buffer.from(root.fingerprint).toString('hex').toUpperCase(), + xpub: root.derivePath(PATH).neutered().toBase58(), + derivationPath: PATH, + }; +} + +function fixture(): RecoverablePolicyDraftInput { + return { + version: 1, + network: NetworkType.TESTNET, + mobile: { + role: 'mobile', + signerType: SignerType.MOBILE_KEY, + ...publicKeyFor(1), + origin: { kind: 'device-generated', version: 1, sourceId: 'test-mobile' }, + }, + hardware: { + role: 'hardware', + signerType: SignerType.COLDCARD, + ...publicKeyFor(2), + origin: { + kind: 'hardware-device', + device: SignerType.COLDCARD, + transport: 'qr', + sourceId: 'test-hardware', + }, + }, + server: { + role: 'server', + signerType: SignerType.POLICY_SERVER, + ...publicKeyFor(3), + origin: { kind: 'keeper-server-key', sourceId: 'test-server-not-enrolled' }, + }, + }; +} + +describe('Assisted Multisig offline testnet script and signing vectors', () => { + test('matches Keeper existing multisig testnet descriptor and receive-address oracle', () => { + // This known public-only descriptor/address is already exercised by + // tests/services/vault.test.ts; it is independent of the new builder. + const test = fixture(); + test.mobile.masterFingerprint = '4192760B'; + test.mobile.xpub = + 'tpubDFCfoi7h1QdAuVVCCBQ8hMdeqcxztV53EB9Qd6cRZ5Tdh94jCPknyhU1mcpCWPzLz2mAVHFdnK1uLKserS1h2sVSJrZvQyghGugQrUpnSrW'; + test.hardware.masterFingerprint = 'AE6E3031'; + test.hardware.xpub = + 'tpubDEbEY1b4Rkaieyi2xUstuVy9ur1be16edv8DrpXqGke2ABqjxoUvxJDLqcdUQmEHyBvgutLwBJ9ciiUijg7cC1A1jKEcxN43xk2W9pMGaCJ'; + test.server.masterFingerprint = 'C7D9EAF5'; + test.server.xpub = + 'tpubDEFf521xjx9TGwajRXBca5bBRNmr9iqa4xLAAytgZ6weCNKKgErF8qgXFGifgYJGF9zLHvPHK6hZHWxeJd4kMkmqcbBMQmCSfnJmUgeNqJ8'; + + const result = deriveRecoverableTestnetScriptVector(test, false, 0); + expect(result.referenceAddress).toBe( + 'tb1qfkv399k9knrjysqvfjt0s352c6pun9v4nmh9uxvacsz57m86cyfsz0runl' + ); + expect(result.descriptor).toBe( + 'wsh(sortedmulti(2,[4192760B/48h/1h/0h/2h]tpubDFCfoi7h1QdAuVVCCBQ8hMdeqcxztV53EB9Qd6cRZ5Tdh94jCPknyhU1mcpCWPzLz2mAVHFdnK1uLKserS1h2sVSJrZvQyghGugQrUpnSrW/<0;1>/*,[AE6E3031/48h/1h/0h/2h]tpubDEbEY1b4Rkaieyi2xUstuVy9ur1be16edv8DrpXqGke2ABqjxoUvxJDLqcdUQmEHyBvgutLwBJ9ciiUijg7cC1A1jKEcxN43xk2W9pMGaCJ/<0;1>/*,[C7D9EAF5/48h/1h/0h/2h]tpubDEFf521xjx9TGwajRXBca5bBRNmr9iqa4xLAAytgZ6weCNKKgErF8qgXFGifgYJGF9zLHvPHK6hZHWxeJd4kMkmqcbBMQmCSfnJmUgeNqJ8/<0;1>/*))#g47ywxzw' + ); + expect(result.kind).toBe('unfundable-testnet-2-of-3-vector'); + expect(result.fundable).toBe(false); + expect(result.scriptPubKey).toEqual(bitcoin.address.toOutputScript(result.referenceAddress, bitcoin.networks.testnet)); + }); + + test('separates receive/change branches and never produces a mainnet address', () => { + const input = fixture(); + const a = deriveRecoverableTestnetScriptVector(input, false, 0); + const b = deriveRecoverableTestnetScriptVector(input, true, 0); + const c = deriveRecoverableTestnetScriptVector(input, false, 1); + expect(new Set([a.referenceAddress, b.referenceAddress, c.referenceAddress]).size).toBe(3); + expect(a.referenceAddress).toMatch(/^tb1q/); + expect(b.referenceAddress).toMatch(/^tb1q/); + expect(a.descriptor).toBe(b.descriptor); + expect(a.descriptor).toBe(c.descriptor); + expect(a.fundable).toBe(false); + }); + + test.each([ + [-1], + [1.25], + [1001], + [Number.NaN], + [Number.POSITIVE_INFINITY], + ])('fails closed for unsupported derivation index %s', (index) => { + expect(() => deriveRecoverableTestnetScriptVector(fixture(), false, index)).toThrow( + RecoverablePolicyDraftError + ); + }); + + test('rejects a nonboolean branch selector and the mainnet network', () => { + expect(() => deriveRecoverableTestnetScriptVector(fixture(), 'false' as never, 0)).toThrow( + RecoverablePolicyDraftError + ); + const input = fixture(); + input.network = NetworkType.MAINNET as never; + expect(() => deriveRecoverableTestnetScriptVector(input, false, 0)).toThrow( + RecoverablePolicyDraftError + ); + }); + + test('rejects a repeated signer before an address is derived', () => { + const input = fixture(); + input.hardware.masterFingerprint = input.mobile.masterFingerprint; + expect(() => deriveRecoverableTestnetScriptVector(input, false, 0)).toThrow( + RecoverablePolicyDraftError + ); + }); + + test('does not reuse the base-2-of-3 script for an inheritance wallet', () => { + const input = fixture(); + input.inheritance = { + signer: { + role: 'inheritance', + signerType: SignerType.SEED_WORDS, + ...publicKeyFor(4), + origin: { kind: 'externally-held-inheritance-key', sourceId: 'heir-test-only' }, + }, + activation: { + kind: 'block-height', + value: 85_012, + observedHeight: 85_000, + observedMedianTimePast: 1_700_000_000, + }, + }; + expect(() => deriveRecoverableTestnetScriptVector(input, false, 0)).toThrow( + /separate verified Miniscript/ + ); + }); + + test.each([ + ['Mobile + Hardware', [0, 1]], + ['Mobile + Server', [0, 2]], + ['Hardware + Server', [1, 2]], + ])('a real BitcoinJS PSBT can be finalized by %s without the third signer', (_, pair) => { + // Test-only deterministic private keys and a synthetic UTXO: this proves + // script/signature satisfaction, NOT network broadcast or server enrollment. + const keys = [1, 2, 3].map((byte) => + bip32.fromSeed(Buffer.alloc(32, byte), bitcoin.networks.testnet) + .derivePath(PATH).derive(0).derive(0) + ); + const vector = deriveRecoverableTestnetScriptVector(fixture(), false, 0); + const makePsbt = () => { + const destination = bitcoin.payments.p2wpkh({ + pubkey: Buffer.from(keys[0].publicKey), + network: bitcoin.networks.testnet, + }).address!; + return new bitcoin.Psbt({ network: bitcoin.networks.testnet }) + .addInput({ + hash: '11'.repeat(32), + index: 0, + witnessUtxo: { script: vector.scriptPubKey, value: 100_000 }, + witnessScript: vector.witnessScript, + }) + .addOutput({ address: destination, value: 99_000 }); + }; + + const insufficient = makePsbt(); + insufficient.signInput(0, keys[pair[0]]); + expect(() => insufficient.finalizeAllInputs()).toThrow(); + + const complete = makePsbt(); + complete.signInput(0, keys[pair[0]]); + complete.signInput(0, keys[pair[1]]); + complete.finalizeAllInputs(); + const witness = complete.extractTransaction().ins[0].witness; + expect(witness).toHaveLength(4); // empty CHECKMULTISIG item + two sigs + witnessScript + expect(witness[0]).toHaveLength(0); + expect(witness[3]).toEqual(vector.witnessScript); + }); +}); From de7a1966879ee21bf481da89b2e17cc259d18467 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:47:39 +0530 Subject: [PATCH 26/31] docs(preview): record first public-only testnet 2-of-3 signing checkpoint and gates --- docs/preview/recoverable-wallet/README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index 8a9e703ba..be06ea627 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -2,7 +2,18 @@ **Approved user-facing chooser name (11 October 2026): Assisted Multisig.** Place it between **Single-Key Wallet** and **Custom Wallet**. The former public-facing name is retired. Keep internal `seedless` route IDs, prop names, storage identifiers and testIDs unchanged until a separately reviewed migration; this is a copy/name decision only, not a cryptographic or security guarantee. -Status (9 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Assisted Multisig" is the **approved** user-facing choice; "Recoverable Wallet" remains an internal working term. +Status (12 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Assisted Multisig" is the **approved** user-facing choice; "Recoverable Wallet" remains an internal working term. + +## First offline 2-of-3 testnet-script checkpoint (12 October 2026) + +The first **functional bitcoin script** work has begun in this same branch without changing any server or production app code: + +- `src/services/wallets/recoverable/testnetScriptVector.ts` derives a real native-segwit `wsh(sortedmulti(2,...))` BIP67 reference script, testnet reference address, and checksummed portable public descriptor from **three already-supplied account-level public keys**. It reuses the existing strict public-policy validation (network, independent fingerprints/xpubs, BIP48 origins), rejects inheritance until its separate Miniscript verification is ready, rejects unbounded derivation indices and clearly types every result `fundable: false`. +- `tests/services/recoverable/testnetScriptVector.test.ts` adds a cross-check against an independent existing Keeper descriptor/address fixture; rejects mainnet, invalid indices, duplicate keys and inheritance substitution; and exercises **all three pairs** (Mobile+Hardware, Mobile+Server, Hardware+Server) against BitcoinJS PSBT signatures with **synthetic non-broadcastable UTXOs**. One signature is insufficient; two signatures should finalize. +- **Validation status:** the module and regression tests are committed in draft PR #7041. CI is required before asserting a pass. Native Mobile Key persistence, physical signer proof, authentic enrolled Server Key, encrypted backups and readback, wallet activation, real testnet UTXO discovery, fee/change review, broadcast, and fresh-phone restoration are **not yet implemented or verified** in this path. +- **Safety invariant:** These computed addresses are *test vectors*, never offered as deposit/receive addresses. No actual funds should be sent; a public server xpub or a draft policy is not proof of a usable signer. The baseline 2-of-3 script is not a substitute for the optional delayed inheritance script. + +Next functional work independent of Adam: runtime-test native Mobile Key create/load/restart and consistency; test hardware provenance/public import and actual connection; integrate **verified** real key material into a testnet-only wallet-activation gate with secure backup, device-policy approval and complete 2-of-3 signing; then run a real testnet send/receive test with a disposable wallet. The Server Key protocol and any feature-specific SigningServer/Relay edits remain on hold for Adam and explicit owner approval. ## First client checkpoint From 9d0a68711d1d22b78351bc3ca809e06bbc6a59bb Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:55:35 +0530 Subject: [PATCH 27/31] feat(preview): add honest local Mobile Key readback diagnostic --- .../recoverable/previewMobileKeyReadback.ts | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/services/wallets/recoverable/previewMobileKeyReadback.ts diff --git a/src/services/wallets/recoverable/previewMobileKeyReadback.ts b/src/services/wallets/recoverable/previewMobileKeyReadback.ts new file mode 100644 index 000000000..3484147c1 --- /dev/null +++ b/src/services/wallets/recoverable/previewMobileKeyReadback.ts @@ -0,0 +1,81 @@ +import * as bitcoin from 'bitcoinjs-lib'; +import { Buffer } from 'buffer'; +import { + DeviceMobileKeyError, + getOrCreatePreviewDeviceMobileKey, +} from './deviceMobileKey'; +import type { RecoverableMobileSigner } from './policyDraft'; + +/** + * A LOCAL, opt-in diagnostic. It may create the native Preview Mobile Key, + * then reads it a second time. No wallet, server key, funding, backup, signing + * authority, or recovery capability is created or implied. + * + * This cannot prove continuity across a process restart or reinstall. The + * public identity must later be bound to durable wallet and recovery records. + */ +export interface PreviewMobileKeyReadbackEvidence { + kind: 'preview-mobile-key-two-read-match'; + network: 'testnet'; + masterFingerprint: string; + /** Short hash of PUBLIC account xpub, not the xpub or private seed itself. */ + publicIdentityTag: string; + matchedReads: 2; + backupVerified: false; + walletReady: false; + recoveryVerified: false; +} + +function isExpectedPreviewSigner(signer: RecoverableMobileSigner): boolean { + return ( + signer?.role === 'mobile' && + signer?.origin?.kind === 'device-generated' && + signer.origin.version === 1 && + signer.derivationPath === "m/48'/1'/0'/2'" && + typeof signer.masterFingerprint === 'string' && + /^[A-F0-9]{8}$/.test(signer.masterFingerprint) && + typeof signer.xpub === 'string' && + signer.xpub.startsWith('tpub') + ); +} + +export async function checkPreviewMobileKeyReadback( + read: () => Promise = getOrCreatePreviewDeviceMobileKey +): Promise { + const first = await read(); + if (!isExpectedPreviewSigner(first)) { + throw new DeviceMobileKeyError( + 'INVALID_PUBLIC_SIGNER', + 'Native Mobile Key returned unexpected public metadata' + ); + } + const second = await read(); + if ( + !isExpectedPreviewSigner(second) || + first.masterFingerprint !== second.masterFingerprint || + first.xpub !== second.xpub || + first.derivationPath !== second.derivationPath || + first.origin.sourceId !== second.origin.sourceId + ) { + throw new DeviceMobileKeyError( + 'MOBILE_KEY_CHANGED', + 'Mobile Key public identity changed between native reads' + ); + } + + // Public, display-only correlation tag: no seed, xprv, or complete xpub. + const tag = Buffer.from(bitcoin.crypto.sha256(Buffer.from(first.xpub, 'utf8'))) + .toString('hex') + .slice(0, 16) + .toUpperCase(); + return { + kind: 'preview-mobile-key-two-read-match', + network: 'testnet', + masterFingerprint: first.masterFingerprint, + publicIdentityTag: tag, + matchedReads: 2, + backupVerified: false, + walletReady: false, + recoveryVerified: false, + }; +} From c5a3a6fa43ee5d9724ddae962396eae78080ab0d Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:55:53 +0530 Subject: [PATCH 28/31] fix(preview): narrow device-generated Mobile Key public origin --- .../wallets/recoverable/previewMobileKeyReadback.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/services/wallets/recoverable/previewMobileKeyReadback.ts b/src/services/wallets/recoverable/previewMobileKeyReadback.ts index 3484147c1..4a6a9d5a7 100644 --- a/src/services/wallets/recoverable/previewMobileKeyReadback.ts +++ b/src/services/wallets/recoverable/previewMobileKeyReadback.ts @@ -26,7 +26,11 @@ export interface PreviewMobileKeyReadbackEvidence { recoveryVerified: false; } -function isExpectedPreviewSigner(signer: RecoverableMobileSigner): boolean { +function isExpectedPreviewSigner( + signer: RecoverableMobileSigner +): signer is RecoverableMobileSigner & { + origin: Extract; +} { return ( signer?.role === 'mobile' && signer?.origin?.kind === 'device-generated' && From 0747777164ea6fb9ffbdea1ff27a17377905b6d1 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:56:23 +0530 Subject: [PATCH 29/31] test(preview): verify Mobile Key continuity evidence and failure gating --- .../previewMobileKeyReadback.test.ts | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 tests/services/recoverable/previewMobileKeyReadback.test.ts diff --git a/tests/services/recoverable/previewMobileKeyReadback.test.ts b/tests/services/recoverable/previewMobileKeyReadback.test.ts new file mode 100644 index 000000000..2185d9c2f --- /dev/null +++ b/tests/services/recoverable/previewMobileKeyReadback.test.ts @@ -0,0 +1,92 @@ +import { Buffer } from 'buffer'; +import { + deriveDeviceMobileKeyPublic, + DeviceMobileKeyError, +} from 'src/services/wallets/recoverable/deviceMobileKey'; +import { checkPreviewMobileKeyReadback } from 'src/services/wallets/recoverable/previewMobileKeyReadback'; + +jest.mock('react-native-config', () => ({ + __esModule: true, + default: { KEEPER_PREVIEW: 'true', KEEPER_PREVIEW_TESTNET_ONLY: 'true' }, +})); +jest.mock('react-native-device-info', () => ({ + __esModule: true, + default: { getBundleId: jest.fn(() => 'io.hexawallet.keeper.recoverablepreview') }, +})); + +const firstSeed = Buffer.alloc(32, 17); +const otherSeed = Buffer.alloc(32, 18); + +describe('testnet Preview local Mobile Key readback evidence', () => { + const mobile = deriveDeviceMobileKeyPublic(firstSeed); + const other = deriveDeviceMobileKeyPublic(otherSeed); + + test('requires two actual public signer reads and returns no secret or full xpub', async () => { + const read = jest.fn(async () => mobile); + const evidence = await checkPreviewMobileKeyReadback(read); + expect(read).toHaveBeenCalledTimes(2); + expect(evidence).toMatchObject({ + kind: 'preview-mobile-key-two-read-match', + network: 'testnet', + masterFingerprint: mobile.masterFingerprint, + matchedReads: 2, + backupVerified: false, + walletReady: false, + recoveryVerified: false, + }); + expect(evidence.publicIdentityTag).toMatch(/^[A-F0-9]{16}$/); + expect(evidence).not.toHaveProperty('xpub'); + const serialized = JSON.stringify(evidence); + expect(serialized).not.toContain(mobile.xpub); + expect(serialized).not.toContain(firstSeed.toString('hex')); + }); + + test('same public identity produces same display tag on repeated verification', async () => { + const a = await checkPreviewMobileKeyReadback(async () => mobile); + const b = await checkPreviewMobileKeyReadback(async () => mobile); + expect(a).toEqual(b); + }); + + test('rejects changed native Mobile Key even when same origin shape is returned', async () => { + const read = jest.fn().mockResolvedValueOnce(mobile).mockResolvedValueOnce(other); + await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + code: 'MOBILE_KEY_CHANGED', + }); + }); + + test('rejects different public key when fingerprint is incorrectly reused', async () => { + const read = jest + .fn() + .mockResolvedValueOnce(mobile) + .mockResolvedValueOnce({ ...other, masterFingerprint: mobile.masterFingerprint }); + await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + code: 'MOBILE_KEY_CHANGED', + }); + }); + + test('rejects unexpected policy origin before claiming readback', async () => { + const read = jest.fn(async () => ({ + ...mobile, + origin: { + kind: 'keeper-recovery-key-bip85', + version: 1, + ordinal: 0, + bip85Index: 1_000_000, + bip85Path: "m/83696968'/39'/0'/12'/1000000'", + }, + })) as never; + await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + code: 'INVALID_PUBLIC_SIGNER', + }); + }); + + test('propagates storage errors without reporting recovery or backup success', async () => { + const read = jest.fn(async () => { + throw new DeviceMobileKeyError('MOBILE_KEY_STORAGE_UNAVAILABLE', 'Store unavailable'); + }); + await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + code: 'MOBILE_KEY_STORAGE_UNAVAILABLE', + }); + expect(read).toHaveBeenCalledTimes(1); + }); +}); From fed6c93554e9e0941b4c31c8ded55d87577c4d48 Mon Sep 17 00:00:00 2001 From: antuz123 <43998049+antuz123@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:58:20 +0530 Subject: [PATCH 30/31] feat(preview): add opt-in native Mobile Key readback screen and backup warning --- .../RecoverableWalletPreviewApp.tsx | 121 +++++++++++++++++- 1 file changed, 116 insertions(+), 5 deletions(-) diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index e86eb7b84..809c1680b 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -16,6 +16,10 @@ import ScreenWrapper from 'src/components/ScreenWrapper'; import WalletCreationChooser, { WalletChoiceCard } from 'src/components/WalletCreationChooser'; import { customTheme } from 'src/navigation/themes'; import Colors from 'src/theme/Colors'; +import { + checkPreviewMobileKeyReadback, + type PreviewMobileKeyReadbackEvidence, +} from 'src/services/wallets/recoverable/previewMobileKeyReadback'; import { ContactDecisionState, ContactEnrollmentState, @@ -57,6 +61,7 @@ type PreviewSurface = | 'advanced' | 'import' | 'seedless' + | 'mobile-key-diagnostic' | 'recovery' | 'cloud' | 'contact'; @@ -208,6 +213,12 @@ function PreviewContent() { initialSimulatedSetupState ); const [showHowItWorks, setShowHowItWorks] = useState(false); + const [deviceKeyDiagnostic, setDeviceKeyDiagnostic] = useState< + | { status: 'idle' | 'checking' } + | { status: 'matched'; evidence: PreviewMobileKeyReadbackEvidence } + | { status: 'failed'; code: string } + >({ status: 'idle' }); + const deviceKeyCheckNumber = useRef(0); const [contactEnrollment, setContactEnrollment] = useState(initialContactEnrollment); const [contactSample, setContactSample] = useState<'overview' | 'invitation' | 'request'>( @@ -242,6 +253,29 @@ function PreviewContent() { setRequestDecision(null); setSurface('recovery'); }; + const checkNativeMobileKey = async () => { + if (deviceKeyDiagnostic.status === 'checking') return; + const checkNumber = ++deviceKeyCheckNumber.current; + setDeviceKeyDiagnostic({ status: 'checking' }); + try { + // This opt-in action MAY create a REAL, device-only TESTNET preview key. + // No wallet, backup, server registration, or signing path is created. + const evidence = await checkPreviewMobileKeyReadback(); + if (checkNumber === deviceKeyCheckNumber.current) { + setDeviceKeyDiagnostic({ status: 'matched', evidence }); + } + } catch (error) { + if (checkNumber === deviceKeyCheckNumber.current) { + // Never display native error detail or secret material in the UI. + const code = error && typeof error === 'object' && 'code' in error && + typeof error.code === 'string' && /^[A-Z_]{3,40}$/.test(error.code) + ? error.code + : 'READBACK_FAILED'; + setDeviceKeyDiagnostic({ status: 'failed', code }); + } + } + }; + const startSampleInvitation = () => { setInvitationDecision('pending'); setContactSample('invitation'); @@ -264,7 +298,7 @@ function PreviewContent() { const back = () => { if (surface === 'cloud' || surface === 'contact') setSurface('recovery'); else if (surface === 'recovery') setSurface('seedless'); - else if (surface === 'chooser') setSurface('wallets'); + else if (surface === 'chooser' || surface === 'mobile-key-diagnostic') setSurface('wallets'); else if (surface === 'simple') setSurface(choiceOrigin); else if (surface === 'hot' || surface === 'cold') setSurface('simple'); else if (surface === 'advanced' || surface === 'import') setSurface(choiceOrigin); @@ -321,7 +355,7 @@ function PreviewContent() { previewNotice={ fromWallets ? undefined - : 'TESTNET PREVIEW · Simulated choices. No wallet, key, address, or backup is created.' + : 'TESTNET PREVIEW · Simulated choices. No wallet, address, or backup is created.' } seedlessResumeHint={ hasDraft ? 'Your Assisted Multisig walkthrough will resume where you left off.' : undefined @@ -349,6 +383,8 @@ function PreviewContent() { ? 'Import Wallet' : surface === 'recovery' ? 'Recovery Options' + : surface === 'mobile-key-diagnostic' + ? 'Local Mobile Key' : surface === 'cloud' ? 'Cloud Backup' : surface === 'contact' @@ -368,10 +404,12 @@ function PreviewContent() { {surface !== 'chooser' && ( {surface === 'wallets' - ? 'TESTNET DEMO · No wallet or key.' + ? 'TESTNET DEMO · No spendable wallet or backup.' : surface === 'seedless' - ? 'TESTNET DEMO · No wallet or key.' - : 'TESTNET PREVIEW · Simulated walkthrough. No wallet, key, address, cloud backup, or server registration is created.'} + ? 'TESTNET DEMO · No spendable wallet or backup.' + : surface === 'mobile-key-diagnostic' + ? 'TESTNET KEY CHECK · A device-only key may be generated without a backup. Never send bitcoin to this preview.' + : 'TESTNET PREVIEW · Simulated walkthrough. No wallet, address, cloud backup, or server registration is created.'} )} @@ -381,6 +419,79 @@ function PreviewContent() { No wallets yet {walletChooser(true)} + setSurface('mobile-key-diagnostic')} + palette={palette} + testID="preview-device-mobile-key-entry" + /> + + )} + + {surface === 'mobile-key-diagnostic' && ( + + + Check local Mobile Key + + + This checks real native Preview key storage, not the simulated wallet setup. It may + create a device-only testnet Mobile Key. Nothing is backed up or recoverable yet. + + + + Native readback + + {deviceKeyDiagnostic.status === 'idle' && ( + + Not tested. No key-storage result is available. + + )} + {deviceKeyDiagnostic.status === 'checking' && ( + + + Checking two native reads… + + )} + {deviceKeyDiagnostic.status === 'matched' && ( + + + Two native reads matched on this device. + + + Public fingerprint: {deviceKeyDiagnostic.evidence.masterFingerprint} + + + Public identity tag: {deviceKeyDiagnostic.evidence.publicIdentityTag} + + + Close the Preview app, reopen it and check again. Compare these public values + manually. This first check does not prove key continuity across a restart. + + + )} + {deviceKeyDiagnostic.status === 'failed' && ( + + Native storage or readback failed ({deviceKeyDiagnostic.code}). Do not use the + key. Nothing has been repaired or replaced. + + )} + + + NOT BACKED UP · No wallet, signing, cloud recovery or Server Key is active. Do not + fund this key. Removing the app can make the key inaccessible. + + { void checkNativeMobileKey(); }} + disabled={deviceKeyDiagnostic.status === 'checking'} + palette={palette} + /> + setSurface('wallets')} + palette={palette} + testID="preview-mobile-key-back" + /> )} From 8c0656d2f41af4e49992b103c687278647d2ef7b Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 12 Oct 2026 06:31:27 +0000 Subject: [PATCH 31/31] Harden isolated preview keys, policy and recovery verification --- .../workflows/recoverable-preview-checks.yml | 55 ++ AGENTS.md | 67 +++ .../KeeperPreviewMobileKeyModule.kt | 168 ++---- .../KeeperPreviewMobileKeyStore.kt | 145 +++++ docs/preview/recoverable-wallet/README.md | 54 +- .../recoverable-wallet/native-preview.md | 21 +- .../recoverable-wallet/policy-draft.md | 4 +- .../KeeperPreviewMobileKey.m | 52 +- .../RecoverableWalletPreviewApp.tsx | 19 +- .../wallets/recoverable/deviceMobileKey.ts | 34 +- .../recoverable/hardwarePublicImport.ts | 56 +- .../wallets/recoverable/policyDraft.ts | 70 ++- .../recoverable/previewMobileKeyBackup.ts | 472 +++++++++++++++ .../recoverable/previewMobileKeyReadback.ts | 66 ++- .../KeeperPreviewMobileKeyStoreTest.kt | 394 +++++++++++++ tests/native/preview-mobile-key/README.md | 43 ++ tests/native/preview-mobile-key/run.sh | 70 +++ .../preview/recoverableWalletScreen.test.tsx | 49 ++ .../recoverable/deviceMobileKey.test.ts | 69 ++- .../recoverable/hardwarePublicImport.test.ts | 98 ++++ .../services/recoverable/policyDraft.test.ts | 125 ++++ .../previewMobileKeyBackup.test.ts | 542 ++++++++++++++++++ .../previewMobileKeyReadback.test.ts | 82 ++- .../recoverable/testnetScriptVector.test.ts | 236 ++++++-- 24 files changed, 2736 insertions(+), 255 deletions(-) create mode 100644 .github/workflows/recoverable-preview-checks.yml create mode 100644 AGENTS.md create mode 100644 android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyStore.kt create mode 100644 src/services/wallets/recoverable/previewMobileKeyBackup.ts create mode 100644 tests/native/preview-mobile-key/KeeperPreviewMobileKeyStoreTest.kt create mode 100644 tests/native/preview-mobile-key/README.md create mode 100644 tests/native/preview-mobile-key/run.sh create mode 100644 tests/services/recoverable/previewMobileKeyBackup.test.ts diff --git a/.github/workflows/recoverable-preview-checks.yml b/.github/workflows/recoverable-preview-checks.yml new file mode 100644 index 000000000..b68d0fbc6 --- /dev/null +++ b/.github/workflows/recoverable-preview-checks.yml @@ -0,0 +1,55 @@ +name: Recoverable Preview checks + +on: + pull_request: + branches: [sprint] + paths: + - '.github/workflows/recoverable-preview-checks.yml' + - 'src/preview/recoverable-wallet/**' + - 'src/services/wallets/recoverable/**' + - 'src/services/wallets/operations/recoverable/**' + - 'tests/preview/**' + - 'tests/services/recoverable/**' + - 'tests/native/preview-mobile-key/**' + - 'android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKey*.kt' + - 'ios/recoverablePreviewMobileKey/**' + - 'package.json' + - 'yarn.lock' + +permissions: + contents: read + +jobs: + native-core: + name: Preview native core and bridge types + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '21' + - name: Check actual Kotlin core and Android bridge types + run: bash tests/native/preview-mobile-key/run.sh --android-bridge-typecheck + + offline-tests: + name: Preview offline regressions + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: '22' + - name: Select Yarn + run: corepack prepare yarn@1.22.22 --activate + - name: Install without native setup or lockfile mutation + run: yarn install --pure-lockfile --ignore-scripts + # The existing live-Electrum suites remain in the repository Tests job. + # These offline checks never receive, broadcast or query real test sats. + - name: Run offline regressions + run: >- + yarn test --runInBand --coverage=false + --testPathIgnorePatterns /node_modules/ + 'tests/services/(client|wallet|vault)\.test\.ts$' diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..7e3d9609c --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,67 @@ +# Bitcoin Keeper: Codex workflow + +This repository uses a **ChatGPT → Codex Cloud → Codex Local (Mac)** workflow for coding tasks. The GitHub pull request is the durable handoff between stages. Do **not** rely on one agent having access to another agent's conversation, unpushed changes, machine, or installed tools. + +Repository: `KeeperCommunity/bitcoin-keeper`. Use `sprint` as the PR base unless the task explicitly specifies another base. + +## Codex Cloud: implement and prepare handoff + +1. Work in a task-specific branch; investigate, implement, add or update tests, and run suitable checks (for example, `npm run test` and `npm run lint`). Report actual pass/fail results; do not claim a native simulator was run unless it really was. +2. Open or update a GitHub PR with the code changes. Preserve the user's existing work; never overwrite or silently discard another branch's changes. +3. Before asking for local testing, add a section named **Codex local handoff** to the PR description (or a fresh PR comment), using this format: + + ```text + ## Codex local handoff + State: NEEDS_LOCAL + PR: # + Base: sprint + Head branch: + Head commit: + Goal and acceptance criteria: + Changes made: + Cloud checks: + Required local checks: IOS, ANDROID + Local checks requested: + Risks / known gaps: + ``` + +4. For app/code changes, `Required local checks` must list one or more of `IOS`, `ANDROID`, `HARDWARE` (comma-separated). Use both iOS and Android for cross-platform changes; add hardware for signer/device interactions. If no Mac tests are necessary, explain why, but the GitHub gate exempts only documentation and `.github/` changes. The handoff must name the actual PR head commit SHA after the final cloud push. +5. Return the PR URL/number and state `NEEDS_LOCAL` to the user so ChatGPT can generate the exact local handoff prompt. Continue unrelated cloud tasks while waiting for a Mac. +6. If a task needs only code review, explicitly state why local testing is not required rather than silently skipping it. + +## Codex Local (Mac): validate the PR + +When given **"Validate Keeper PR #"**, first read the newest **Codex local handoff** section and inspect the PR head SHA. + +1. Fetch the PR branch into a separate worktree or another safe checkout. Never reset, clean, or overwrite uncommitted user changes. +2. Verify the exact tested commit. Perform the **requested** native build and simulator/emulator scenarios using the available local tools. The repo defines an iPhone simulator script (`npm run ios`), Android development script (`npm run androidDevelopmentDebug`), and Jest tests. Do not assume signing credentials, device access, or an emulator are configured. +3. Run relevant regression checks and record outcomes. If hardware-wallet, NFC, USB, camera, or real-device behaviour matters, distinguish physical-device tests actually performed from tests requiring a person/device. +4. If bugs are found, make targeted fixes on the PR branch when permitted, push those changes, and retest the new SHA. +5. Leave a PR comment in this format: + + ```text + ## Codex local validation + State: LOCAL_PASSED | LOCAL_FAILED | BLOCKED + Tested commit: + iOS build/simulator: + Android build/emulator: + Real devices/signers: + Other checks: + Open issues / next action: + Release readiness: + ``` + +6. Report the result and PR link to ChatGPT/the user. + +## Release safety and coordination + +- `LOCAL_PASSED` means only the reported checks passed on the reported commit. It is **not** approval to merge, sign, distribute, upload to TestFlight/Play Store, or publish a release. +- Release operations require **explicit user approval** for the intended build, environment, and distribution channel. +- ChatGPT is the coordinator: when the user shares a PR or asks for a handoff/status, inspect the latest PR details and comments; then provide the next exact copy-and-paste prompt for Cloud or Local Codex. ChatGPT should not claim to know Codex's private session state or that the Mac is currently available. +- If the Mac is offline, the state remains `NEEDS_LOCAL`; cloud work does not have to stop. + +## GitHub merge gate + +The `.github/workflows/keeper-local-validation.yml` workflow posts commit status `keeper/local-validation` for the current PR head SHA. For code changes, it remains failing until a repository collaborator posts a `Codex local validation` comment with `State: LOCAL_PASSED`, the **exact current commit SHA**, and `pass` for every platform named by `Required local checks`. New commits invalidate previous local sign-off. Documentation and `.github/`-only PRs are exempt from Mac tests. + +This workflow **reports** a status; to **enforce** it, repository administrators must require the `keeper/local-validation` commit status for merges to `sprint` in GitHub Rulesets or branch protection. Require the existing `Tests` CI check as well. This is a review/test gate, not a guarantee that tests were actually executed; agents must report actual results truthfully. Release signing, TestFlight, Play Store, and production deployment remain separate and require explicit user approval. diff --git a/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt index e3bc7931c..11544e211 100644 --- a/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt +++ b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt @@ -7,15 +7,9 @@ import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import io.hexawallet.keeper.BuildConfig -import java.io.File -import java.io.RandomAccessFile import java.security.KeyStore -import java.security.MessageDigest -import java.security.SecureRandom -import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey -import javax.crypto.spec.GCMParameterSpec import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties @@ -27,22 +21,46 @@ class KeeperPreviewMobileKeyModule( @ReactMethod fun getOrCreateSeedBase64(promise: Promise) { + resolveSeed(promise, createIfMissing = true) + } + + @ReactMethod + fun readExistingSeedBase64(promise: Promise) { + resolveSeed(promise, createIfMissing = false) + } + + private fun resolveSeed(promise: Promise, createIfMissing: Boolean) { if (!BuildConfig.IS_RECOVERABLE_PREVIEW || context.packageName != PREVIEW_PACKAGE) { promise.reject("PREVIEW_ONLY", "Mobile Key requires the testnet preview app") return } try { - // The monitor protects threads; the file lock protects a second app process. - val encoded = synchronized(processLock) { - val directory = context.noBackupFilesDir - if (!directory.isDirectory) throw IllegalStateException("No-backup storage unavailable") - RandomAccessFile(File(directory, LOCK_FILE), "rw").use { lockFile -> - lockFile.channel.use { channel -> - channel.lock().use { getOrCreateLocked(directory) } + val files = KeeperPreviewMobileKeyFiles(context.noBackupFilesDir) + val atomicFile = AtomicFile(files.seedFile) + val records = object : KeeperPreviewMobileKeyRecords { + override fun read(): ByteArray = atomicFile.openRead().use { + KeeperPreviewMobileKeyRecord.readBounded(it) + } + + override fun writeDurably(record: ByteArray) { + val stream = atomicFile.startWrite() + try { + stream.write(record) + atomicFile.finishWrite(stream) + } catch (error: Exception) { + atomicFile.failWrite(stream) + throw error } } } + val seed = KeeperPreviewMobileKeyStore(files, records, AndroidEncryptionKeys()) + .getSeed(createIfMissing) + val encoded = try { + Base64.encodeToString(seed, Base64.NO_WRAP) + } finally { + seed.fill(0) + } promise.resolve(encoded) } catch (_: Exception) { // Never replace an unreadable, corrupted, or inaccessible existing key. @@ -50,118 +68,38 @@ class KeeperPreviewMobileKeyModule( } } - private fun getOrCreateLocked(directory: File): String { - val seedFile = File(directory, SEED_FILE) - val atomicFile = AtomicFile(seedFile) - // A lone .new file is an interrupted AtomicFile write, not an empty store. - // Never replace a possible prior seed after a crash. - val hasAnyRecord = seedFile.exists() || - File(seedFile.path + ".bak").exists() || File(seedFile.path + ".new").exists() - val key = getOrCreateEncryptionKey(hasAnyRecord) - - if (hasAnyRecord) { - val seed = decrypt(atomicFile.readFully(), key) - return try { - Base64.encodeToString(seed, Base64.NO_WRAP) - } finally { - seed.fill(0) - } - } + private class AndroidEncryptionKeys : KeeperPreviewMobileKeyEncryptionKeys { + // Initialize only under the core's process and file locks. + private val keyStore by lazy { KeyStore.getInstance("AndroidKeyStore").apply { load(null) } } - val seed = ByteArray(SEED_LENGTH) - SecureRandom().nextBytes(seed) - try { - val ciphertext = encrypt(seed, key) - val stream = atomicFile.startWrite() - try { - stream.write(ciphertext) - atomicFile.finishWrite(stream) - } catch (error: Exception) { - atomicFile.failWrite(stream) - throw error - } - - // Do not expose a newly generated seed unless durable storage reads it back. - val readback = decrypt(atomicFile.readFully(), key) - return try { - if (!MessageDigest.isEqual(seed, readback)) { - throw IllegalStateException("Mobile Key readback differs") - } - Base64.encodeToString(seed, Base64.NO_WRAP) - } finally { - readback.fill(0) - } - } finally { - seed.fill(0) - } - } - - private fun getOrCreateEncryptionKey(recordExists: Boolean): SecretKey { - val keyStore = KeyStore.getInstance("AndroidKeyStore") - keyStore.load(null) - val existing = keyStore.getKey(KEY_ALIAS, null) - if (existing != null) { - // The alias can precede the first durable seed write. A crash in - // that window is ambiguous, so require a manual preview reset. - if (!recordExists) throw IllegalStateException("Mobile Key record is missing") + override fun read(): SecretKey? { + val existing = keyStore.getKey(KEY_ALIAS, null) ?: return null return existing as? SecretKey ?: throw IllegalStateException("Mobile Key encryption key is invalid") } - if (recordExists || keyStore.containsAlias(KEY_ALIAS)) { - throw IllegalStateException("Mobile Key encryption key is missing") - } - - val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") - generator.init( - KeyGenParameterSpec.Builder( - KEY_ALIAS, - KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT - ) - .setBlockModes(KeyProperties.BLOCK_MODE_GCM) - .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) - .setKeySize(256) - .setRandomizedEncryptionRequired(true) - .setUserAuthenticationRequired(false) - .build() - ) - return generator.generateKey() - } - private fun encrypt(seed: ByteArray, key: SecretKey): ByteArray { - val cipher = Cipher.getInstance("AES/GCM/NoPadding") - cipher.init(Cipher.ENCRYPT_MODE, key) - cipher.updateAAD(PREVIEW_PACKAGE.toByteArray(Charsets.UTF_8)) - val iv = cipher.iv - if (iv.size != IV_LENGTH) throw IllegalStateException("Invalid Mobile Key nonce") - val encrypted = cipher.doFinal(seed) - return byteArrayOf(RECORD_VERSION) + iv + encrypted - } + override fun containsAlias() = keyStore.containsAlias(KEY_ALIAS) - private fun decrypt(record: ByteArray, key: SecretKey): ByteArray { - if (record.size != 1 + IV_LENGTH + SEED_LENGTH + TAG_LENGTH || - record[0] != RECORD_VERSION - ) { - throw IllegalStateException("Invalid Mobile Key record") + override fun create(): SecretKey { + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + generator.init( + KeyGenParameterSpec.Builder( + KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .setRandomizedEncryptionRequired(true) + .setUserAuthenticationRequired(false) + .build() + ) + return generator.generateKey() } - val iv = record.copyOfRange(1, 1 + IV_LENGTH) - val encrypted = record.copyOfRange(1 + IV_LENGTH, record.size) - val cipher = Cipher.getInstance("AES/GCM/NoPadding") - cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv)) - cipher.updateAAD(PREVIEW_PACKAGE.toByteArray(Charsets.UTF_8)) - val seed = cipher.doFinal(encrypted) - if (seed.size != SEED_LENGTH) throw IllegalStateException("Invalid Mobile Key seed") - return seed } private companion object { - const val PREVIEW_PACKAGE = "io.hexawallet.keeper.recoverablepreview" + const val PREVIEW_PACKAGE = KeeperPreviewMobileKeyRecord.PREVIEW_PACKAGE const val KEY_ALIAS = "$PREVIEW_PACKAGE.mobile-key.v1" - const val SEED_FILE = "keeper-preview-mobile-key-v1.bin" - const val LOCK_FILE = "keeper-preview-mobile-key-v1.lock" - const val SEED_LENGTH = 32 - const val IV_LENGTH = 12 - const val TAG_LENGTH = 16 - const val RECORD_VERSION: Byte = 1 - val processLock = Any() } } diff --git a/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyStore.kt b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyStore.kt new file mode 100644 index 000000000..1c2d7dadd --- /dev/null +++ b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyStore.kt @@ -0,0 +1,145 @@ +package com.hexa_keeper + +import java.io.File +import java.io.InputStream +import java.io.RandomAccessFile +import java.security.MessageDigest +import java.security.SecureRandom +import javax.crypto.Cipher +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** Platform-neutral parts of the preview store; Android supplies Keystore and AtomicFile. */ +internal class KeeperPreviewMobileKeyFiles(private val directory: File) { + val seedFile = File(directory, "keeper-preview-mobile-key-v1.bin") + private val lockFile = File(directory, "keeper-preview-mobile-key-v1.lock") + + fun hasAnyRecord() = seedFile.exists() || + File(seedFile.path + ".bak").exists() || File(seedFile.path + ".new").exists() + + fun withLock(block: () -> T): T = synchronized(processLock) { + if (!directory.isDirectory) { + throw IllegalStateException("No-backup storage unavailable") + } + // Hold both locks across record IO and Keystore access, including readback. + RandomAccessFile(lockFile, "rw").use { file -> + file.channel.use { channel -> channel.lock().use { block() } } + } + } + + private companion object { + val processLock = Any() + } +} + +internal interface KeeperPreviewMobileKeyRecords { + fun read(): ByteArray + fun writeDurably(record: ByteArray) +} + +internal interface KeeperPreviewMobileKeyEncryptionKeys { + fun read(): SecretKey? + fun containsAlias(): Boolean + fun create(): SecretKey +} + +internal class KeeperPreviewMobileKeyStore( + private val files: KeeperPreviewMobileKeyFiles, + private val records: KeeperPreviewMobileKeyRecords, + private val keys: KeeperPreviewMobileKeyEncryptionKeys, + private val fillRandom: (ByteArray) -> Unit = { SecureRandom().nextBytes(it) } +) { + /** Caller owns the returned buffer and must clear it immediately after bridge encoding. */ + fun getSeed(createIfMissing: Boolean): ByteArray = files.withLock { + val hasAnyRecord = files.hasAnyRecord() + if (!createIfMissing && !hasAnyRecord) { + throw IllegalStateException("Mobile Key record is missing") + } + val key = encryptionKey(hasAnyRecord) + if (hasAnyRecord) { + KeeperPreviewMobileKeyRecord.decrypt(records.read(), key) + } else { + val seed = ByteArray(KeeperPreviewMobileKeyRecord.SEED_LENGTH) + try { + fillRandom(seed) + records.writeDurably(KeeperPreviewMobileKeyRecord.encrypt(seed, key)) + // Return only the seed actually read from committed storage. + val readback = KeeperPreviewMobileKeyRecord.decrypt(records.read(), key) + if (!MessageDigest.isEqual(seed, readback)) { + readback.fill(0) + throw IllegalStateException("Mobile Key readback differs") + } + readback + } finally { + seed.fill(0) + } + } + } + + private fun encryptionKey(recordExists: Boolean): SecretKey { + val existing = keys.read() + if (existing != null) { + // An alias without a record can be a crash before the first durable write. + if (!recordExists) throw IllegalStateException("Mobile Key record is missing") + return existing + } + if (recordExists || keys.containsAlias()) { + throw IllegalStateException("Mobile Key encryption key is missing") + } + return keys.create() + } +} + +/** Versioned, authenticated record format shared by the Android store and JVM checks. */ +internal object KeeperPreviewMobileKeyRecord { + const val PREVIEW_PACKAGE = "io.hexawallet.keeper.recoverablepreview" + const val SEED_LENGTH = 32 + private const val IV_LENGTH = 12 + private const val TAG_LENGTH = 16 + private const val RECORD_VERSION: Byte = 1 + private const val RECORD_LENGTH = 1 + IV_LENGTH + SEED_LENGTH + TAG_LENGTH + + /** A corrupted file must not cause readFully to allocate an unbounded buffer. */ + fun readBounded(input: InputStream): ByteArray { + val record = ByteArray(RECORD_LENGTH) + var offset = 0 + while (offset < record.size) { + val count = input.read(record, offset, record.size - offset) + if (count <= 0) throw IllegalStateException("Invalid Mobile Key record") + offset += count + } + if (input.read() != -1) throw IllegalStateException("Invalid Mobile Key record") + return record + } + + fun encrypt(seed: ByteArray, key: SecretKey): ByteArray { + if (seed.size != SEED_LENGTH) throw IllegalStateException("Invalid Mobile Key seed") + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, key) + cipher.updateAAD(PREVIEW_PACKAGE.toByteArray(Charsets.UTF_8)) + val iv = cipher.iv + if (iv.size != IV_LENGTH) throw IllegalStateException("Invalid Mobile Key nonce") + return byteArrayOf(RECORD_VERSION) + iv + cipher.doFinal(seed) + } + + fun decrypt(record: ByteArray, key: SecretKey): ByteArray { + if (record.size != RECORD_LENGTH || + record[0] != RECORD_VERSION + ) { + throw IllegalStateException("Invalid Mobile Key record") + } + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init( + Cipher.DECRYPT_MODE, + key, + GCMParameterSpec(128, record.copyOfRange(1, 1 + IV_LENGTH)) + ) + cipher.updateAAD(PREVIEW_PACKAGE.toByteArray(Charsets.UTF_8)) + val seed = cipher.doFinal(record.copyOfRange(1 + IV_LENGTH, record.size)) + if (seed.size != SEED_LENGTH) { + seed.fill(0) + throw IllegalStateException("Invalid Mobile Key seed") + } + return seed + } +} diff --git a/docs/preview/recoverable-wallet/README.md b/docs/preview/recoverable-wallet/README.md index be06ea627..ed3908566 100644 --- a/docs/preview/recoverable-wallet/README.md +++ b/docs/preview/recoverable-wallet/README.md @@ -1,51 +1,37 @@ # Recoverable Wallet — parallel Keeper preview -**Approved user-facing chooser name (11 October 2026): Assisted Multisig.** Place it between **Single-Key Wallet** and **Custom Wallet**. The former public-facing name is retired. Keep internal `seedless` route IDs, prop names, storage identifiers and testIDs unchanged until a separately reviewed migration; this is a copy/name decision only, not a cryptographic or security guarantee. +**Approved chooser name: Assisted Multisig**, between Single-Key Wallet and Custom Wallet. Recoverable Wallet is the internal working term. Keep existing route IDs, storage identifiers and testIDs until a separately reviewed migration. -Status (12 October 2026): **isolated client preview and direct three-choice empty Wallets entry implemented; the current Android preview APK built and launched; iOS package configured but not built**. This is a simulated walkthrough, not a released or security-reviewed wallet. "Assisted Multisig" is the **approved** user-facing choice; "Recoverable Wallet" remains an internal working term. +Status (12 October 2026): **isolated, testnet-only engineering preview; wallet setup remains simulated and unfundable**. The optional Test Mobile Key diagnostic can create a real, unbacked-up device key. Offline script, signing and encrypted recovery fixtures now exercise functional cryptography, but do not create a usable wallet, hardware session, cloud backup or Server Key. -## First offline 2-of-3 testnet-script checkpoint (12 October 2026) +## Current engineering checkpoint -The first **functional bitcoin script** work has begun in this same branch without changing any server or production app code: +| Area | Functional behavior and evidence | Remaining boundary | +| --- | --- | --- | +| Preview UI | Empty Wallets chooser; simulated Mobile/Server setup, hardware, inheritance, final review and recovery decisions. Tests ensure native diagnostics run only after an explicit Check Key action. | No wallet or signing authority is created by setup. | +| Mobile Key | Exact Preview identity guards; native create/load followed by a **read-only** reload, canonical BIP48 public identity checks and immutable observation snapshots. Android core passes 21 Kotlin/JVM cases; bridge types compile against real API 36 / React Native 0.83.9 classes. | No current APK or iOS build, actual Keystore/AtomicFile/Keychain execution, restart/reinstall or physical-device proof in this Cloud checkpoint. | +| Public policy/import | Reject repeated underlying account public keys despite relabelled tpub metadata/chain codes; reject malformed inheritance, quorum overrides, hidden private data and unsafe export objects. | Imports do not establish possession, device authenticity, policy approval or manufacturer support. | +| Base signing | BIP67 P2WSH vectors plus synthetic-UTXO PSBT tests for all three pairs, receive/change and boundary indices. Verify final-transaction ECDSA witnesses and reject input/output/amount/signature/order tampering and outsider keys. | No Bitcoin Core consensus execution, native signer use, real UTXO, deposit UI, broadcast or independent external-wallet exit. | +| Encrypted recovery | Disconnected local fixtures use actual Node PBKDF2-SHA256/AES-256-GCM. Authenticated versioned envelopes bind exact independently held policy, Mobile identity and credential context; write acknowledgement alone cannot produce readback evidence. 49 focused cases passed. | Native crypto defaults unavailable. No iCloud/Drive identity, upload, native key import, fresh-phone restore or contact wrapping protocol. | +| Server/inheritance | Existing public policy compiler candidates and visibly simulated decisions only. | Authentic Server Key enrollment awaits Adam and approval. Inheritance needs separate consensus, maturity and complete hardware-policy validation. | -- `src/services/wallets/recoverable/testnetScriptVector.ts` derives a real native-segwit `wsh(sortedmulti(2,...))` BIP67 reference script, testnet reference address, and checksummed portable public descriptor from **three already-supplied account-level public keys**. It reuses the existing strict public-policy validation (network, independent fingerprints/xpubs, BIP48 origins), rejects inheritance until its separate Miniscript verification is ready, rejects unbounded derivation indices and clearly types every result `fundable: false`. -- `tests/services/recoverable/testnetScriptVector.test.ts` adds a cross-check against an independent existing Keeper descriptor/address fixture; rejects mainnet, invalid indices, duplicate keys and inheritance substitution; and exercises **all three pairs** (Mobile+Hardware, Mobile+Server, Hardware+Server) against BitcoinJS PSBT signatures with **synthetic non-broadcastable UTXOs**. One signature is insufficient; two signatures should finalize. -- **Validation status:** the module and regression tests are committed in draft PR #7041. CI is required before asserting a pass. Native Mobile Key persistence, physical signer proof, authentic enrolled Server Key, encrypted backups and readback, wallet activation, real testnet UTXO discovery, fee/change review, broadcast, and fresh-phone restoration are **not yet implemented or verified** in this path. -- **Safety invariant:** These computed addresses are *test vectors*, never offered as deposit/receive addresses. No actual funds should be sent; a public server xpub or a draft policy is not proof of a usable signer. The baseline 2-of-3 script is not a substitute for the optional delayed inheritance script. +The seed store remains a **diagnostic preview foundation**. Android uses Keystore-encrypted no-backup storage under process/file locks, bounded authenticated records and durable readback. iOS uses a non-synchronizing WhenUnlockedThisDeviceOnly Keychain item and create-if-absent/readback. Both now expose a read-only operation that never creates a missing record. Generated/owned mutable buffers are cleared on exits, but immutable native/base64/JavaScript strings and BIP32 copies cannot be reliably erased. These are not non-exportable or proven hardware-backed signing keys; independent security review is required before activation. -Next functional work independent of Adam: runtime-test native Mobile Key create/load/restart and consistency; test hardware provenance/public import and actual connection; integrate **verified** real key material into a testnet-only wallet-activation gate with secure backup, device-policy approval and complete 2-of-3 signing; then run a real testnet send/receive test with a disposable wallet. The Server Key protocol and any feature-specific SigningServer/Relay edits remain on hold for Adam and explicit owner approval. +The two-read evidence proves only an immediate public identity match. It always reports `backupVerified: false`, `recoveryVerified: false` and `walletReady: false`. Record public values externally before restart/reinstall testing; do not treat a matching short display tag as a policy or recovery authorization. -## First client checkpoint +`previewMobileKeyBackup.ts` is a **local-fixture-only foundation**, disconnected from the app. It requires 32 independently generated recovery-secret bytes, fresh salt/nonce requests, fixed bounded crypto parameters and an independently held complete base testnet policy. Verification authenticates the envelope and re-derives the exact fingerprint/account tpub from the decrypted 32-byte seed, returning evidence only. It never returns/imports a seed or replaces native storage. All results keep `cloudBackupVerified`, `nativeRestoreVerified` and `walletReady` false. Inheritance is rejected until its separate recovery validation exists. Actual credential custody, policy persistence, rollback protection and cloud/native restore remain future work. -- The current package starts at the empty **Wallets** screen with Single-Key, Assisted Multisig, and Custom choices; Add Wallet opens the same chooser. Assisted Multisig walks through automatic Mobile Key / Server Key ready statuses, hardware selection, a simulated connection/error, optional Inheritance Key, one final whole-policy review, and completion. Cancel and resume work while the app stays open. No key, wallet, address, backup, transaction, hardware session, or server registration is created. -- TAPSIGNER, Satochip, Jade, and Coldcard appear with their existing Keeper transport choices. The UI says policy verification and full Recoverable Wallet compatibility remain unproven. Every simulated status, error, and completion is labeled. The latest source offers only the base 2-of-3 proposal for TAPSIGNER, Satochip, and Jade; Coldcard alone can proceed to an explicitly unverified Inheritance Key proposal. -- The app entry requires the exact preview package ID and testnet-only preview flags. Normal Keeper continues through its original app component. The preview loads no wallet store, cloud backup, signing, or server client. The native preview identifiers are distinct, the Android CloudBackup module is disabled, and the iOS preview has no iCloud entitlement. See [native-preview.md](native-preview.md). -- An arm64 Android debug APK with an embedded JavaScript bundle was built and its package identity and debug signature checked. It installed and ran beside both a Keeper development app and the public production Keeper v2.6.3 APK on an Android emulator. Side-by-side installation and storage isolation on physical devices remain unverified. The iOS preview scheme, identifier, plist, and entitlements are configured, but an iOS build has not been run: this checkout lacks matching Pods and has insufficient free disk space for a safe fresh install/build. +## Verification and local acceptance -| Evidence | Current result | -| --- | --- | -| Simulated client flow | Automated walkthrough covers four hardware choices, cancel/resume, connection error, inheritance choice, and final review. | -| Startup boundary and related regressions | 108 focused Jest tests pass across 14 preview and related service suites. | -| Native build | Android arm64 debug APK built with embedded JS, installed and launched on an arm64 emulator; iOS scheme configuration inspected, build pending. | -| Small-screen rendering | Android emulator walkthrough passed at 320dp width and 1.6× system font: statuses, four hardware choices, simulated error, inheritance, review, and completion remained scrollable and actionable. The Jest content check alone does not establish rendered layout. | -| Physical devices and production side-by-side installation | Production v2.6.3 and Preview co-installed and launched on the emulator. Physical installation and cross-app storage isolation are pending. | -| Cryptography, cloud read-back, physical hardware, security review | Pending. A device-generated Mobile Key service is unit tested but remains unwired and is not a wallet-ready state. | +Reproducible native core/bridge checks and their limits are in [tests/native/preview-mobile-key/README.md](../../../tests/native/preview-mobile-key/README.md). [native-preview.md](native-preview.md) records app identities and the device checklist. The latest **Codex local handoff** in [draft PR #7041](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7041) names the exact pushed commit, final Cloud counts and required IOS, ANDROID, HARDWARE checks. -The next owner test is to install the Android APK beside normal Keeper, walk through both inheritance choices and a simulated error, verify text and controls at a small screen width with larger system font, then uninstall Preview and confirm the normal app and backups remain intact. Equivalent iOS testing follows a fresh matching Pods install, simulator/device build, and preview App ID/provisioning setup. Do not use real wallet funds or production recovery material in either preview. +Focused Cloud checks passed: 50 Mobile Key/diagnostic UI cases, 66 policy/import/signing cases, and 49 encrypted recovery cases. TypeScript comparison against `fed6c93554e9e0941b4c31c8ded55d87577c4d48` found identical 1,010 existing diagnostics and none in edited preview files. Full ESLint fails with 4,554 errors / 919 warnings; touched-source diagnostics have no additions against that head. The final full Jest run passed 32 suites / 363 tests and failed 3 existing live-Electrum suites / 40 tests after connection errors; it required `--forceExit` because those clients retain handles. Focused or offline results must not be described as a repository-wide pass. The dedicated Recoverable Preview checks workflow runs the native core/bridge harness and offline regressions; repository Tests remains separate and includes the live-Electrum suites. -## Second client checkpoint in this branch +A frozen dependency install fails because the existing manifest/lockfile needs reconciliation. Cloud installed with `yarn install --pure-lockfile --ignore-scripts`; no package/lockfile or R4/Reproducibility changes were included. This is a known tooling limitation, not reproducible native-build evidence. -- The separate preview app starts with **no wallet** and the three choices directly on Wallets: **Single-Key Wallet** (phone or signing device next), prominent **Assisted Multisig**, and **Custom Wallet**; Import Wallet remains visible. The same chooser is retained for Add Wallet. The labels describe setup paths, without a “Featured” badge or a blanket seed-word promise on the card. Single-Key, Custom, and Import explain their preview limits. A guarded normal-app entry and no-default-hot-wallet setup path are also coded, but their gate requires the exact testnet preview identity; that identity currently launches the isolated shell. They are deliberately dormant until an integrated preview runtime can be reviewed. With the gate off, normal Keeper retains its existing wallet creation behavior. -- Selecting Assisted Multisig immediately starts a compact, simulated progress screen rather than a mandatory introduction: Mobile Key then Server Key status labels advance in order, Hardware Key waits for the user, and **Choose Hardware** enables only after both demo steps. “How it works” is optional in-flow detail; the complete policy remains a required review before any real wallet could be created. The timer changes labels only: it creates no key, backup, server registration, or wallet. A future real “Added” status must wait for verified secure Mobile Key persistence or Server Key registration, respectively; elapsed time cannot establish readiness. -- The default Assisted Multisig design calls for an independently generated Mobile Key and no new seed words for the user to record. Derivation from Keeper's existing 12-word Recovery Key remains an **optional creation path**, not a setup prerequisite or chooser message. The isolated BIP85 helper reserves a versioned child range starting at index 1,000,000; Keeper already reserves 0–99 for default hot wallets and 100–199 for USDT, so the first or tenth child must not be shared with Assisted Multisig. Its pure allocator refuses to reuse an ordinal, including after deletion, but it is **not connected to wallet creation**: Realm lacks the durable reservation ledger, tombstones, and atomic backup mapping it requires. A Recovery Key cannot recreate a separately generated Mobile Key by derivation alone; that would require a reviewed encrypted backup or wrapping design. -- A public-only testnet policy builder validates distinct Mobile/Hardware/Server keys, BIP48 account tpub shape, supported import transports, and an optional absolute Inheritance Key locktime before the final review. A separate pure importer accepts public Coldcard/Jade BIP48 testnet exports and marks both the device and policy **not verified**; it does not open a device or connect to the UI. The 2-of-3 and delayed 2-of-4 policy results remain explicitly **unfundable**. The inheritance Miniscript is a review candidate, not a verified descriptor or hardware registration. See [policy-draft.md](policy-draft.md). -- A client-only Recovery Contact state model covers encrypted-cloud readback receipts, offline retry, invitation/request expiry, approval/decline, and optional recovery-code gating. It stops before cryptographic enrollment or restoration. No contact key, encrypted backup, native cloud container, or independent exchange channel exists yet. See [recovery-contact.md](recovery-contact.md). -- The isolated preview now lets the owner explore Recovery Options after the Assisted Multisig walkthrough: separate Cloud Backup and Recovery Contact screens show unverified readback, simulated offline/retry, sample invitation and lost-phone decisions, decline, and expiry. Every screen states that no key, encrypted blob, contact credential, approval response, or restored Mobile Key exists. These are decision samples, not an operational recovery path. -- Proposed inheritance behavior is a fixed on-chain unlock date selected before wallet creation, with no reset on app open; changing it later requires a new wallet and on-chain transfer. The heir needs the Inheritance Key **and** an accessible original signer independent of the Server Key. The preview labels this proposal as unconfigured. Product decisions about fixed versus renewed timing, an extra contact recovery code, and the heir's second signer are pending owner answers. +Historical Android evidence belongs to older commits: at `86f4be0265f37a9ee7ebc2f9c5f6a2ec97ada1d6`, an embedded-JS arm64 debug APK built, installed beside production Keeper v2.6.3 on an emulator, and displayed the three-choice Wallets entry. A preceding walkthrough exercised 320dp width / 1.6× text. These checks do **not** validate the current native changes. iOS has not been built. Physical co-installation, sandbox/Keychain isolation and uninstall safety remain open. -The latest client code passed **108 Jest tests across 14 focused suites** covering the direct empty Wallets entry, simulated Mobile/Server failure and retry, Add Wallet chooser, preview isolation, hardware-dependent inheritance gating, Recovery Key education gate, native Mobile Key bridge error handling, public Coldcard/Jade export validation, key-origin policy draft, contact states, and Recovery Key migration. The latest arm64 APK embeds this chooser, shorter copy, simulated setup error/retry states, and Android's preview-only native Mobile Key module. An Android emulator walkthrough at 320dp and 1.6× system font confirmed that the three-choice landing, Mobile/Server statuses, hardware action, persistent setup error sample, and retry remain reachable by scrolling. The complete hardware, inheritance, and final-review walkthrough at that size was recorded against the preceding package; those flow stages did not change in this package. The temporary local Metro symlink adjustment was removed after packaging. - -The separate `deviceMobileKey.ts` service is **not called by the preview UI or wallet creation**. It can derive a testnet BIP48 public Mobile signer from the new preview-only native seed store. Android uses a Keystore-encrypted no-backup record under a file lock; iOS uses a non-sync, ThisDeviceOnly Keychain record with create-if-absent. Both native modules check the installed preview identity, and Android preview compilation passed. This is preparation for a real flow, not proof of a safe fundable key: native storage has not been runtime-tested, iOS has not been fully built, the seed crosses the native-to-JavaScript bridge for derivation, and key continuity after reinstall must be tied to an existing wallet policy before creation can be connected to real readiness. Encrypted backup and recovery remain absent. +The first spendable disposable testnet checkpoint needs reviewed native storage/recovery, verified hardware and whole-policy confirmation, genuine Server Key registration, and independently verified 2-of-3 send/receive and exit. Keep reference addresses unfundable and the normal app unchanged. No mainnet, production backup access, backend implementation, merge, release or distribution is authorized by this checkpoint. Keep this stream independent of R4 and Reproducibility. ## Owner decision (8 October 2026) diff --git a/docs/preview/recoverable-wallet/native-preview.md b/docs/preview/recoverable-wallet/native-preview.md index 296a672cf..7c29003aa 100644 --- a/docs/preview/recoverable-wallet/native-preview.md +++ b/docs/preview/recoverable-wallet/native-preview.md @@ -1,6 +1,6 @@ # Native preview packaging (milestone 1) -The preview runs the simulated Recoverable Wallet flow only. It creates no wallet, has no signing or recovery protocol, and cannot reach Keeper's production server endpoints from its checked-in configuration. +The Recoverable Wallet setup and recovery flow remain simulated. The separate opt-in Test Mobile Key diagnostic can create a real, unbacked-up testnet device key. It creates no wallet, signing authority or recovery protocol, and the checked-in configuration cannot reach Keeper's production service endpoints. | Platform | Preview identity | Build entry | Storage/cloud boundary | | --- | --- | --- | --- | @@ -9,7 +9,9 @@ The preview runs the simulated Recoverable Wallet flow only. It creates no walle Both builds use the checked-in `.env.recoverable-preview` file. It sets `KEEPER_PREVIEW=true`, `KEEPER_PREVIEW_TESTNET_ONLY=true` and local unreachable service URLs. The preview entry also checks the exact native bundle/application ID before showing the flow; mismatches show a locked error screen. The preview runtime does not initialize the normal Keeper app or its wallet store. -The preview-only native Mobile Key module is registered only in the Android `recoverablePreview` flavor and compiled only in the iOS preview scheme's development target. It checks the exact installed app ID again before using device-only secure storage. Its JavaScript service remains uncalled by the walkthrough; the visible Mobile Key status is still simulated. Android native code compiles, while iOS compilation and both platforms' runtime storage behavior remain unverified. Before any real wallet can be funded, test create/load, interrupted writes, corruption, reinstall continuity, and seed exposure through the JavaScript bridge, then establish recovery and policy-bound key identity. +The preview-only native Mobile Key module is registered only in the Android `recoverablePreview` flavor and compiled only in the iOS preview scheme. Both create/load and read-only reload check the exact installed Preview identity. **Test Mobile Key → Check Key** invokes it; the Assisted Multisig setup statuses remain simulated. The second diagnostic read cannot create a replacement, and malformed or changed public identities fail rather than becoming wallet-ready. + +Current Cloud checks: 21 actual Android storage-core JVM cases and a narrow Kotlin bridge typecheck against real API 36 / React Native 0.83.9 classes (generated BuildConfig fixture). See [native harness](../../../tests/native/preview-mobile-key/README.md). This does not execute Keystore, AtomicFile or iOS Security, produce an APK/IPA, or prove restart/reinstall continuity. The seed still crosses the native-to-JavaScript bridge; mutable-buffer clearing cannot erase immutable strings/BIP32 copies. Keep native/security review and recovery validation mandatory before a fundable path. ## Build and install @@ -33,7 +35,7 @@ The local verification worktree shared `node_modules` through a symlink. Metro r The Android package must be installed alongside production Keeper and verified on a device before calling the milestone device-tested. The iOS scheme is configured for the simulator, but a simulator build has not yet completed. A signed physical-device build requires an Apple App ID and provisioning profile for `io.hexawallet.hexakeeper.recoverablepreview`; distribution access must be checked with the Keeper team. Neither cloud backup nor a physical hardware connection is claimed by this milestone. -Local Android emulator verification on 9 October 2026: the current arm64 APK installed and launched from its embedded JavaScript bundle at 320dp width with 1.6× system text. The shorter testnet demo notice leaves the Assisted Multisig option visible on the empty Wallets screen; Mobile and Server simulated statuses and Choose Hardware remain reachable by scrolling. The persistent Show Setup Error action, simulated Server Key failure, and Try Again recovery were exercised in the native app. Keeper Preview, an existing development app, and the public production Keeper v2.6.3 APK had distinct package IDs and launched on the same emulator. The preceding package also completed the simulated hardware, connection error, inheritance, review, and completion walkthrough at that size. Physical-device installation and real storage/keychain separation still require checks. +Historical Android emulator verification on 9 October 2026 (older source, not the current native changes): the arm64 APK installed and launched from its embedded JavaScript bundle at 320dp width with 1.6× system text. The shorter testnet demo notice leaves the Assisted Multisig option visible on the empty Wallets screen; Mobile and Server simulated statuses and Choose Hardware remain reachable by scrolling. The persistent Show Setup Error action, simulated Server Key failure, and Try Again recovery were exercised in the native app. Keeper Preview, an existing development app, and the public production Keeper v2.6.3 APK had distinct package IDs and launched on the same emulator. The preceding package also completed the simulated hardware, connection error, inheritance, review, and completion walkthrough at that size. Physical-device installation and real storage/keychain separation still require checks. Before future cloud backup work, register a dedicated iCloud container for the preview App ID and dedicated Google OAuth/Drive credentials. Keep access disabled until read-back and cross-app isolation are verified on real devices. Do not reuse Keeper's production or development cloud identities. @@ -44,3 +46,16 @@ Before future cloud backup work, register a dedicated iCloud container for the p 3. Check iOS Keychain and Android app data remain inaccessible to the other app. On iOS, inspect the signed preview entitlements; they must contain no production iCloud or Keychain group. 4. Confirm both preview backends use only local unreachable URLs and the UI has no mainnet control, wallet creation, signing, or cloud-backup action. 5. Uninstall Preview and confirm production Keeper and its wallet/backups remain intact. + +## Mobile Key runtime acceptance (current code) + +Use disposable Preview data only; record the exact tested commit and installed identity. Keep production Keeper installed and never inspect or modify its keys/backups. + +1. Before creating a key, call `readExistingSeedBase64`: it must fail without creating a seed or Keystore alias/Keychain item. Check Key may then create the diagnostic key; repeat and compare the same public BIP48 identity. Backup/recovery/wallet readiness must stay false. +2. Force-stop/terminate Preview, reopen and repeat. Record full public identity in a local test harness separately from the displayed short tag. Test parallel calls and app/background/locked-device transitions; failures must show only safe codes. +3. Android: in a disposable debug Preview sandbox, mutate/truncate/oversize the encrypted record, remove the alias with the record retained, remove the record with the alias retained, and interrupt first write. A lone `.new`/`.bak` artifact or unreadable record must never trigger replacement. A valid AtomicFile backup may restore only its original identity. Exercise actual process/file locks and Keystore behavior. +4. iOS: exercise locked/unlocked Keychain access, missing-item read-only load, corrupt/wrong-length items and duplicate creation against Security.framework. Validate ThisDeviceOnly/non-sync attributes and signed Preview access groups. No simulator result proves physical Keychain behavior. +5. Reinstall expectations differ: Android uninstall normally removes app data/Keystore; iOS Keychain may survive uninstall. Compare against independently recorded policy identity. A fresh key or retained key must never be called a recovered wallet without authenticated backup/native restore proof. Uninstalling Preview must leave production Keeper untouched. +6. Build both exact-head Preview packages, co-install beside production, inspect package IDs/entitlements/no-backup/no-cloud/deep links, run 320dp/larger-text walkthroughs, and test real TAPSIGNER/Satochip/Jade/Coldcard transports before claiming compatibility. Public imports alone are insufficient. + +Native backup/import, credential/policy persistence and actual hardware signing remain absent. No diagnostic reset or restoration into native storage is implemented by the fixture service. diff --git a/docs/preview/recoverable-wallet/policy-draft.md b/docs/preview/recoverable-wallet/policy-draft.md index a934dbc2f..33fdf549b 100644 --- a/docs/preview/recoverable-wallet/policy-draft.md +++ b/docs/preview/recoverable-wallet/policy-draft.md @@ -4,7 +4,7 @@ The Mobile Key may have either public origin: `device-generated` (the default Assisted Multisig setup path, with an opaque public source reference) or `keeper-recovery-key-bip85` (an optional deterministic recreation path using the version 1 BIP85 reservation outside the existing hot-wallet and USDT ranges). The second origin is valid only when its ordinal, index, and BIP85 path agree. The first origin is **not** deterministically recreatable from Keeper's Recovery Key. Enabling RK-assisted recovery of a device-generated Mobile Key would require a separately designed and verified wrapped-backup protocol; none exists in this draft. The source reference and origin tag cannot prove that native generation, secure storage, or backup occurred. -All signers need a testnet BIP48 native-segwit account tpub with serialized depth 4 and final hardened child index `2'`. Duplicate fingerprints or tpubs, private fields, mainnet keys, and unsupported import transports are rejected. A tpub **cannot prove** its claimed earlier derivation ancestors, master fingerprint, device identity, or possession; those need device-specific checks before wallet creation. +All signers need a testnet BIP48 native-segwit account tpub with serialized depth 4 and final hardened child index `2'`. Duplicate fingerprints, encoded tpubs or underlying account public keys are rejected, including relabelled BIP32 metadata and changed chain codes. Private fields, malformed inheritance/quorum overrides, inherited/accessor data, mainnet keys and unsupported import transports are rejected. A tpub **cannot prove** its claimed earlier derivation ancestors, master fingerprint, device identity, or possession; those need device-specific checks before wallet creation. Without Inheritance Key, the review contains Keeper's plain 2-of-3 `VaultScheme`, but no fundable wallet. With Inheritance Key, Keeper's Miniscript policy generator/compiler validates a candidate base 2-of-3 phase and delayed 2-of-4 phase. The review deliberately omits a fundable `MiniscriptScheme` or descriptor. The candidate proves only script compilation and modeled witness paths; it does **not** establish that a particular hardware firmware can display, register, or sign the complete policy. TAPSIGNER, Satochip, and Jade are blocked for this delayed-policy draft because current integrations do not verify the whole policy on-device. Coldcard remains a review candidate, with full hardware-policy compatibility still unproven. The Server Key's genuine public material and registration also remain unavailable until the held server work is reviewed. @@ -13,3 +13,5 @@ Inheritance activation is an explicit absolute block height or median-time-past Exercise the time-dependent flow in three distinct ways: a visibly simulated before/after walkthrough for UX, a disposable public-testnet wallet with a short lock labeled in actual blocks and a real pre-maturity failure/post-maturity spend, and a private regtest chain for fast automated block advancement. Never let a changed phone clock or simulation state unlock a real wallet. Before final policy approval the user can cancel or change the choice; after funding, revoking or extending an inheritance path requires a new policy and a complete on-chain sweep, followed by monitoring of the old addresses. Focused tests cover testnet-only inputs, public-key origin shape, duplicate rejection, optional delayed script/witness combinations, blocked hardware combinations, future locktime, and the non-fundable result. Actual receive/send, physical signer compatibility, descriptor import into another wallet, chain maturity, and server-independent heir exit still require separate tests and review. + +The offline signing vector tests verify final-transaction ECDSA witnesses for each base signer pair using synthetic UTXOs, with input/output/amount/signature/order and outsider-key failures. Hardware import additionally audits all public export fields for concealed private extended keys, bounded size/depth, cycles and non-JSON values. These are fixture/security-boundary checks: no real hardware, Bitcoin Core consensus, network broadcast or Server Key enrollment is asserted. diff --git a/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m b/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m index 684f1eb7e..3a8b23919 100644 --- a/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m +++ b/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m @@ -1,5 +1,4 @@ #import -#import #if defined(KEEPER_RECOVERABLE_PREVIEW) && KEEPER_RECOVERABLE_PREVIEW @@ -22,7 +21,14 @@ }; } -static OSStatus KeeperPreviewReadSeed(NSData **seed) +static void KeeperPreviewClearSeed(NSMutableData *seed) +{ + // Volatile writes keep clearing of owned native buffers from being optimized away. + volatile uint8_t *bytes = (volatile uint8_t *)seed.mutableBytes; + for (NSUInteger index = 0; index < seed.length; index++) bytes[index] = 0; +} + +static OSStatus KeeperPreviewReadSeed(NSMutableData **seed) { CFTypeRef result = NULL; OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)KeeperPreviewSeedQuery(), &result); @@ -34,11 +40,15 @@ static OSStatus KeeperPreviewReadSeed(NSData **seed) if (result != NULL) CFRelease(result); return errSecDecode; } - *seed = CFBridgingRelease(result); + NSData *value = CFBridgingRelease(result); + *seed = [value mutableCopy]; return [(*seed) length] == 32 ? errSecSuccess : errSecDecode; } @interface KeeperPreviewMobileKey : NSObject +- (void)resolveSeedWithCreation:(BOOL)createIfMissing + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject; @end @implementation KeeperPreviewMobileKey @@ -52,6 +62,19 @@ + (BOOL)requiresMainQueueSetup RCT_EXPORT_METHOD(getOrCreateSeedBase64:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) +{ + [self resolveSeedWithCreation:YES resolver:resolve rejecter:reject]; +} + +RCT_EXPORT_METHOD(readExistingSeedBase64:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) +{ + [self resolveSeedWithCreation:NO resolver:resolve rejecter:reject]; +} + +- (void)resolveSeedWithCreation:(BOOL)createIfMissing + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject { NSBundle *bundle = [NSBundle mainBundle]; if (![[bundle bundleIdentifier] isEqualToString:KeeperPreviewBundleID] || @@ -61,19 +84,23 @@ + (BOOL)requiresMainQueueSetup } @synchronized([KeeperPreviewMobileKey class]) { - NSData *stored = nil; + NSMutableData *stored = nil; OSStatus status = KeeperPreviewReadSeed(&stored); if (status == errSecSuccess) { - resolve([stored base64EncodedStringWithOptions:0]); + NSString *encoded = [stored base64EncodedStringWithOptions:0]; + KeeperPreviewClearSeed(stored); + resolve(encoded); return; } - if (status != errSecItemNotFound) { + KeeperPreviewClearSeed(stored); + if (status != errSecItemNotFound || !createIfMissing) { reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); return; } NSMutableData *created = [NSMutableData dataWithLength:32]; if (SecRandomCopyBytes(kSecRandomDefault, created.length, created.mutableBytes) != errSecSuccess) { + KeeperPreviewClearSeed(created); reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); return; } @@ -88,22 +115,25 @@ + (BOOL)requiresMainQueueSetup }; status = SecItemAdd((__bridge CFDictionaryRef)item, NULL); if (status != errSecSuccess && status != errSecDuplicateItem) { - memset(created.mutableBytes, 0, created.length); + KeeperPreviewClearSeed(created); reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); return; } - NSData *readback = nil; + NSMutableData *readback = nil; OSStatus readStatus = KeeperPreviewReadSeed(&readback); if (readStatus != errSecSuccess || (status == errSecSuccess && ![readback isEqualToData:created])) { - memset(created.mutableBytes, 0, created.length); + KeeperPreviewClearSeed(created); + KeeperPreviewClearSeed(readback); reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); return; } // SecItemAdd is create-if-absent. On a duplicate, use the winner's seed. - resolve([readback base64EncodedStringWithOptions:0]); - memset(created.mutableBytes, 0, created.length); + NSString *encoded = [readback base64EncodedStringWithOptions:0]; + KeeperPreviewClearSeed(readback); + KeeperPreviewClearSeed(created); + resolve(encoded); } } diff --git a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx index 809c1680b..4cafd0bea 100644 --- a/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -267,10 +267,14 @@ function PreviewContent() { } catch (error) { if (checkNumber === deviceKeyCheckNumber.current) { // Never display native error detail or secret material in the UI. - const code = error && typeof error === 'object' && 'code' in error && - typeof error.code === 'string' && /^[A-Z_]{3,40}$/.test(error.code) - ? error.code - : 'READBACK_FAILED'; + const code = + error && + typeof error === 'object' && + 'code' in error && + typeof error.code === 'string' && + /^[A-Z_]{3,40}$/.test(error.code) + ? error.code + : 'READBACK_FAILED'; setDeviceKeyDiagnostic({ status: 'failed', code }); } } @@ -435,7 +439,8 @@ function PreviewContent() { This checks real native Preview key storage, not the simulated wallet setup. It may - create a device-only testnet Mobile Key. Nothing is backed up or recoverable yet. + create a device-only testnet Mobile Key. The second read cannot create a replacement. + Nothing is backed up or recoverable yet. @@ -482,7 +487,9 @@ function PreviewContent() { { void checkNativeMobileKey(); }} + onPress={() => { + void checkNativeMobileKey(); + }} disabled={deviceKeyDiagnostic.status === 'checking'} palette={palette} /> diff --git a/src/services/wallets/recoverable/deviceMobileKey.ts b/src/services/wallets/recoverable/deviceMobileKey.ts index 54c66ede4..b3c44c67d 100644 --- a/src/services/wallets/recoverable/deviceMobileKey.ts +++ b/src/services/wallets/recoverable/deviceMobileKey.ts @@ -15,6 +15,8 @@ const RECORD_VERSION = 1 as const; /** A narrow seam for native preview key creation; tests never touch a real key store. */ export interface DeviceMobileKeyAdapters { getOrCreateSeedBase64(): Promise; + /** Read-only: must never create a replacement if the native record is absent. */ + readExistingSeedBase64?(): Promise; } export class DeviceMobileKeyError extends Error { @@ -46,7 +48,8 @@ export function deriveDeviceMobileKeyPublic(seed: Uint8Array): RecoverableMobile } function decodeNativeSeed(base64: string): Buffer { - if (typeof base64 !== 'string') { + // Bound allocation before decoding any untrusted bridge result. + if (typeof base64 !== 'string' || base64.length !== 44) { throw new DeviceMobileKeyError('INVALID_NATIVE_SEED', 'Native Mobile Key is invalid'); } const seed = Buffer.from(base64, 'base64'); @@ -83,6 +86,20 @@ const inFlight = new Map>(); */ export function getOrCreatePreviewDeviceMobileKey( adapter?: DeviceMobileKeyAdapters +): Promise { + return readPreviewDeviceMobileKey('getOrCreateSeedBase64', adapter); +} + +/** Reload an existing key without granting permission to generate another one. */ +export function readExistingPreviewDeviceMobileKey( + adapter?: DeviceMobileKeyAdapters +): Promise { + return readPreviewDeviceMobileKey('readExistingSeedBase64', adapter); +} + +function readPreviewDeviceMobileKey( + operation: 'getOrCreateSeedBase64' | 'readExistingSeedBase64', + adapter?: DeviceMobileKeyAdapters ): Promise { let bundleId: string; try { @@ -103,18 +120,25 @@ export function getOrCreatePreviewDeviceMobileKey( ); } - const pending = inFlight.get(bundleId); + const requestId = `${bundleId}:${operation}`; + const pending = inFlight.get(requestId); if (pending) return pending; let chosen: DeviceMobileKeyAdapters; try { chosen = adapter ?? nativeAdapter(); + if (typeof chosen[operation] !== 'function') { + throw new DeviceMobileKeyError( + 'NATIVE_KEY_UNAVAILABLE', + 'Native Mobile Key operation is unavailable' + ); + } } catch (error) { return Promise.reject(error); } let nativeSeed: Promise; try { - nativeSeed = chosen.getOrCreateSeedBase64(); + nativeSeed = chosen[operation]!(); } catch (error) { return Promise.reject(error); } @@ -126,9 +150,9 @@ export function getOrCreatePreviewDeviceMobileKey( seed.fill(0); } }); - inFlight.set(bundleId, task); + inFlight.set(requestId, task); const clear = () => { - if (inFlight.get(bundleId) === task) inFlight.delete(bundleId); + if (inFlight.get(requestId) === task) inFlight.delete(requestId); }; void task.then(clear, clear); return task; diff --git a/src/services/wallets/recoverable/hardwarePublicImport.ts b/src/services/wallets/recoverable/hardwarePublicImport.ts index ccf29ad02..1682b9cd8 100644 --- a/src/services/wallets/recoverable/hardwarePublicImport.ts +++ b/src/services/wallets/recoverable/hardwarePublicImport.ts @@ -51,7 +51,12 @@ function fail(code: string, message: string): never { } function asRecord(value: unknown): PublicRecord { - if (!value || typeof value !== 'object' || Array.isArray(value)) { + if ( + !value || + typeof value !== 'object' || + Array.isArray(value) || + ![Object.prototype, null].includes(Object.getPrototypeOf(value)) + ) { fail('INVALID_HARDWARE_EXPORT', 'Expected a public hardware export object'); } return value as PublicRecord; @@ -74,20 +79,55 @@ function assertPublicPayload(payload: PublicRecord): void { const seen = new Set(); const pending: { value: unknown; depth: number }[] = [{ value: payload, depth: 0 }]; let nodes = 0; + let characters = 0; while (pending.length) { const { value, depth } = pending.pop()!; if (++nodes > MAX_EXPORT_NODES || depth > MAX_EXPORT_DEPTH) { fail('INVALID_HARDWARE_EXPORT', 'Hardware export is too large or deeply nested'); } + if ( + ['undefined', 'function', 'symbol', 'bigint'].includes(typeof value) || + (typeof value === 'number' && !Number.isFinite(value)) + ) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware export must contain JSON data only'); + } + if (typeof value === 'string') { + characters += value.length; + if (characters > MAX_JSON_LENGTH) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware export contains too much string data'); + } + // An unused xpub field or note must not conceal an extended private key. + // Field names alone cannot establish that an export is public-only. + if (/(?:[xtyzuv]prv|[YZUV]prv)[1-9A-HJ-NP-Za-km-z]{100,}/.test(value)) { + fail('PRIVATE_MATERIAL', 'Hardware export must contain public data only'); + } + } if (!value || typeof value !== 'object') continue; + if ( + (!Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value))) || + Object.getOwnPropertySymbols(value).length + ) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware export must contain JSON data only'); + } if (seen.has(value)) fail('INVALID_HARDWARE_EXPORT', 'Hardware export must be acyclic'); seen.add(value); - for (const [key, child] of Object.entries(value)) { + const fields = Object.getOwnPropertyNames(value).filter( + (key) => !Array.isArray(value) || key !== 'length' + ); + for (const key of fields) { + characters += key.length; + if (characters > MAX_JSON_LENGTH) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware export contains too much string data'); + } + const descriptor = Object.getOwnPropertyDescriptor(value, key)!; + if (descriptor.get || descriptor.set) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware export must contain public data values only'); + } const field = key.toLowerCase().replace(/[^a-z0-9]/g, ''); if (PRIVATE_FIELD_NAMES.has(field)) { fail('PRIVATE_MATERIAL', 'Hardware export must contain public data only'); } - pending.push({ value: child, depth: depth + 1 }); + pending.push({ value: descriptor.value, depth: depth + 1 }); } } } @@ -146,10 +186,18 @@ export function importRecoverableHardwarePublicData( if (!input || typeof input !== 'object' || Array.isArray(input)) { fail('INVALID_HARDWARE_EXPORT', 'Hardware import requires explicit device and source'); } - for (const field of Object.keys(input)) { + asRecord(input); + if (Object.getOwnPropertySymbols(input).length) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware import must contain public data fields only'); + } + for (const field of Object.getOwnPropertyNames(input)) { if (!['device', 'transport', 'payload', 'sourceId'].includes(field)) { fail('UNEXPECTED_FIELD', 'Hardware import has an unexpected field'); } + const descriptor = Object.getOwnPropertyDescriptor(input, field)!; + if (descriptor.get || descriptor.set) { + fail('INVALID_HARDWARE_EXPORT', 'Hardware import must contain public data values only'); + } } const payload = parsePayload(input.payload); assertPublicPayload(payload); diff --git a/src/services/wallets/recoverable/policyDraft.ts b/src/services/wallets/recoverable/policyDraft.ts index d138e6225..9b4d62b90 100644 --- a/src/services/wallets/recoverable/policyDraft.ts +++ b/src/services/wallets/recoverable/policyDraft.ts @@ -1,5 +1,6 @@ import BIP32Factory from 'bip32'; import * as bitcoin from 'bitcoinjs-lib'; +import { Buffer } from 'buffer'; import { MultisigScriptType, NetworkType, SignerType } from '../enums'; import type { MiniscriptElements, VaultScheme } from '../interfaces/vault'; import { generateMiniscript } from '../operations/miniscript/miniscript'; @@ -163,15 +164,45 @@ function nonEmptyPublicId(value: unknown, field: string): string { if (typeof value !== 'string' || !value.trim() || value.length > 256) { fail('INVALID_ORIGIN', `${field} must be a non-empty public reference`); } + if (/(?:[xtyzuv]prv|[YZUV]prv)[1-9A-HJ-NP-Za-km-z]{100,}/.test(value)) { + fail('PRIVATE_MATERIAL', `${field} must not contain private key material`); + } return value.trim(); } function assertOnlyKeys(value: object, allowed: readonly string[], field: string): void { - for (const key of Object.keys(value)) { - if (['xpriv', 'mnemonic', 'seed', 'recoveryKey'].includes(key)) { + if ( + !value || + typeof value !== 'object' || + Array.isArray(value) || + ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || + Object.getOwnPropertySymbols(value).length + ) { + fail('INVALID_POLICY_DATA', `${field} must be a public data object`); + } + for (const key of Object.getOwnPropertyNames(value)) { + const normalizedKey = key.toLowerCase().replace(/[^a-z0-9]/g, ''); + if ( + [ + 'xpriv', + 'xprv', + 'tprv', + 'mnemonic', + 'seed', + 'seedhex', + 'recoverykey', + 'privatekey', + 'masterprivatekey', + 'wif', + ].includes(normalizedKey) + ) { fail('PRIVATE_MATERIAL', `${field} must not contain private key material`); } if (!allowed.includes(key)) fail('UNEXPECTED_FIELD', `${field} contains an unexpected field`); + const descriptor = Object.getOwnPropertyDescriptor(value, key)!; + if (descriptor.get || descriptor.set) { + fail('INVALID_POLICY_DATA', `${field} must contain public data values only`); + } } } @@ -179,12 +210,13 @@ function normalizePublicSigner( signer: T, role: T['role'] ): T { - if (!signer || signer.role !== role) fail('INVALID_ROLE', `Expected ${role} signer`); + if (!signer) fail('INVALID_ROLE', `Expected ${role} signer`); assertOnlyKeys( signer, ['role', 'signerType', 'masterFingerprint', 'xpub', 'derivationPath', 'origin'], role ); + if (signer.role !== role) fail('INVALID_ROLE', `Expected ${role} signer`); const fingerprint = typeof signer.masterFingerprint === 'string' ? signer.masterFingerprint.toUpperCase() : ''; if (!/^[0-9A-F]{8}$/.test(fingerprint || '')) { @@ -221,11 +253,18 @@ function validateMobile(signer: RecoverableMobileSigner): RecoverableMobileSigne normalized.signerType !== SignerType.MOBILE_KEY || normalized.derivationPath !== MOBILE_KEY_SIGNER_PATH || !normalized.origin || - typeof normalized.origin !== 'object' || - normalized.origin.version !== 1 + typeof normalized.origin !== 'object' ) { fail('INVALID_MOBILE_ORIGIN', 'Mobile Key requires a supported version 1 public origin'); } + assertOnlyKeys( + normalized.origin, + ['kind', 'version', 'sourceId', 'ordinal', 'bip85Index', 'bip85Path'], + 'Mobile origin' + ); + if (normalized.origin.version !== 1) { + fail('INVALID_MOBILE_ORIGIN', 'Mobile Key requires a supported version 1 public origin'); + } let origin: RecoverableMobileOrigin; if (normalized.origin.kind === 'device-generated') { @@ -335,6 +374,8 @@ function validateInheritance(choice: RecoverableInheritanceChoice): RecoverableI } if ( signer.origin?.kind !== 'externally-held-inheritance-key' || + !Object.values(SignerType).includes(signer.signerType) || + signer.signerType === SignerType.UNKOWN_SIGNER || signer.signerType === SignerType.POLICY_SERVER || signer.signerType === SignerType.MOBILE_KEY ) { @@ -396,12 +437,24 @@ function validateInheritance(choice: RecoverableInheritanceChoice): RecoverableI function assertDistinctSigners(signers: RecoverablePublicSignerBase[]) { const fingerprints = new Set(); const xpubs = new Set(); + const accountPubkeys = new Set(); for (const signer of signers) { - if (fingerprints.has(signer.masterFingerprint) || xpubs.has(signer.xpub)) { + // Fingerprints and BIP32 origin bytes are caller-supplied metadata. Changing + // them (or the chain code) must not make the same account signing key count + // as an independently held policy role. Full ancestry still needs device proof. + const accountPubkey = Buffer.from( + bip32.fromBase58(signer.xpub, bitcoin.networks.testnet).publicKey + ).toString('hex'); + if ( + fingerprints.has(signer.masterFingerprint) || + xpubs.has(signer.xpub) || + accountPubkeys.has(accountPubkey) + ) { fail('DUPLICATE_KEY', 'Each policy role must have independent key material'); } fingerprints.add(signer.masterFingerprint); xpubs.add(signer.xpub); + accountPubkeys.add(accountPubkey); } } @@ -478,7 +531,10 @@ export function buildRecoverablePolicyReview( const mobile = validateMobile(input.mobile); const hardware = validateRecoverableHardwareSigner(input.hardware); const server = validateServer(input.server); - const inheritance = input.inheritance ? validateInheritance(input.inheritance) : null; + const inheritance = + input.inheritance === undefined || input.inheritance === null + ? null + : validateInheritance(input.inheritance); assertDistinctSigners([mobile, hardware, server, ...(inheritance ? [inheritance.signer] : [])]); // These NFC cards can sign, but cannot verify the complete delayed policy on-device. diff --git a/src/services/wallets/recoverable/previewMobileKeyBackup.ts b/src/services/wallets/recoverable/previewMobileKeyBackup.ts new file mode 100644 index 000000000..f83f59e4a --- /dev/null +++ b/src/services/wallets/recoverable/previewMobileKeyBackup.ts @@ -0,0 +1,472 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import { Buffer } from 'buffer'; +import { NetworkType } from '../enums'; +import { RECOVERABLE_MOBILE_KEY_SIGNER_PATH } from '../operations/recoverable/mobileKeyConstants'; +import ecc from '../operations/taproot-utils/noble_ecc'; +import { + buildRecoverablePolicyReview, + type RecoverableMobileSigner, + type RecoverablePolicyDraftInput, +} from './policyDraft'; + +const bip32 = BIP32Factory(ecc); +const KDF_ITERATIONS = 600_000; +const MAX_ENVELOPE_BYTES = 4096; + +/** + * Disconnected CLIENT-ONLY foundation, not a native/cloud backup implementation. + * Only local fixtures may inject cryptography/transport. An omitted adapter + * fails closed: there is no RN crypto, Keychain, Drive, iCloud or server fallback. + * No wallet creation, secret import, seed read or signing API is called here. + */ +export interface PreviewBackupFixtureCrypto { + kind: 'local-fixture-crypto' | 'unavailable'; + randomBytes(length: number): Promise; + /** PBKDF2-HMAC-SHA256, fixed iterations, exactly 32 output bytes. */ + deriveKey(secret: Uint8Array, salt: Uint8Array, iterations: number): Promise; + /** AES-256-GCM, 12-byte nonce, 16-byte authentication tag; authenticate all AAD. */ + encrypt( + key: Uint8Array, + nonce: Uint8Array, + plaintext: Uint8Array, + aad: Uint8Array + ): Promise<{ ciphertext: Uint8Array; tag: Uint8Array }>; + /** Return plaintext only AFTER GCM authentication succeeds. */ + decrypt( + key: Uint8Array, + nonce: Uint8Array, + ciphertext: Uint8Array, + tag: Uint8Array, + aad: Uint8Array + ): Promise; +} + +export interface PreviewBackupFixtureContext { + scope: 'recoverable-preview-local-fixture'; + network: NetworkType.TESTNET; + /** Independently held public references, never passwords or access tokens. */ + backupId: string; + credentialId: string; +} + +export interface PreviewBackupExpectation { + /** Trusted policy held independently of the encrypted record/transport. */ + policy: RecoverablePolicyDraftInput; + context: PreviewBackupFixtureContext; + /** Exactly 32 independently generated high-entropy bytes; not the Mobile seed. */ + recoverySecret: Uint8Array; +} + +interface BackupHeader extends PreviewBackupFixtureContext { + version: 1; + purpose: 'preview-mobile-key-local-backup'; + policyDigest: string; + mobileIdentityDigest: string; + kdf: { algorithm: 'pbkdf2-hmac-sha256'; iterations: 600000; saltHex: string }; + cipher: { algorithm: 'aes-256-gcm'; nonceHex: string; tagBytes: 16 }; +} + +interface BackupEnvelope { + header: BackupHeader; + ciphertextHex: string; + tagHex: string; +} + +export interface PreviewBackupFixtureEvidence { + kind: 'local-fixture-mobile-key-backup-verified'; + network: NetworkType.TESTNET; + backupId: string; + policyDigest: string; + mobileIdentityDigest: string; + authenticatedEncryptionVerified: true; + exactMobileIdentityMatched: true; + /** A write acknowledgement alone never produces readback evidence. */ + exactFixtureReadbackVerified: boolean; + cloudBackupVerified: false; + nativeRestoreVerified: false; + walletReady: false; +} + +export interface PreviewBackupFixtureTransport { + kind: 'local-fixture'; + write(backupId: string, encryptedEnvelope: string): Promise; + read(backupId: string): Promise; +} + +export class PreviewMobileKeyBackupError extends Error { + constructor(public readonly code: string, message: string) { + super(message); + this.name = 'PreviewMobileKeyBackupError'; + } +} + +function fail(code: string, message: string): never { + throw new PreviewMobileKeyBackupError(code, message); +} + +function unavailable(): never { + return fail('NATIVE_BACKUP_UNAVAILABLE', 'Native preview backup crypto is not implemented'); +} + +export const UNAVAILABLE_PREVIEW_BACKUP_CRYPTO: PreviewBackupFixtureCrypto = { + kind: 'unavailable', + randomBytes: async () => unavailable(), + deriveKey: async () => unavailable(), + encrypt: async () => unavailable(), + decrypt: async () => unavailable(), +}; + +function requireFixtureCrypto(crypto: PreviewBackupFixtureCrypto): void { + if ( + crypto?.kind !== 'local-fixture-crypto' || + ['randomBytes', 'deriveKey', 'encrypt', 'decrypt'].some( + (name) => typeof crypto[name] !== 'function' + ) + ) + unavailable(); +} + +function exactKeys(value: unknown, keys: string[]): void { + if ( + !value || + typeof value !== 'object' || + Array.isArray(value) || + ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || + Object.keys(value).length !== keys.length || + keys.some((key) => !Object.prototype.hasOwnProperty.call(value, key)) + ) + fail('INVALID_BACKUP_FORMAT', 'Invalid preview backup record shape'); +} + +function validateContext(context: PreviewBackupFixtureContext): PreviewBackupFixtureContext { + exactKeys(context, ['scope', 'network', 'backupId', 'credentialId']); + if ( + context.scope !== 'recoverable-preview-local-fixture' || + context.network !== NetworkType.TESTNET + ) { + fail('TESTNET_FIXTURE_ONLY', 'Backup fixtures require the isolated testnet preview scope'); + } + for (const value of [context.backupId, context.credentialId]) { + if (typeof value !== 'string' || !/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) { + fail('INVALID_BACKUP_CONTEXT', 'Backup context requires bounded public references'); + } + } + return { + scope: 'recoverable-preview-local-fixture', + network: NetworkType.TESTNET, + backupId: context.backupId, + credentialId: context.credentialId, + }; +} + +function digest(value: unknown): string { + return Buffer.from(bitcoin.crypto.sha256(Buffer.from(JSON.stringify(value), 'utf8'))).toString( + 'hex' + ); +} + +function mobileIdentity(signer: RecoverableMobileSigner): string { + return digest([ + signer.role, + signer.signerType, + signer.masterFingerprint, + signer.derivationPath, + signer.xpub, + ]); +} + +function expectedBinding(expected: PreviewBackupExpectation) { + const context = validateContext(expected?.context); + // Delayed inheritance remains blocked until its script, hardware and recovery + // behavior are independently validated. Never silently back up only its base. + if (expected.policy?.inheritance !== undefined && expected.policy.inheritance !== null) { + fail('INHERITANCE_BACKUP_UNVERIFIED', 'Inheritance backup is not validated'); + } + const review = buildRecoverablePolicyReview(expected.policy); + const mobile = review.base.signers[0]; + if (mobile.origin.kind !== 'device-generated') { + fail('UNSUPPORTED_MOBILE_ORIGIN', 'Fixtures require a device-generated Mobile Key policy'); + } + return { + context, + mobile, + policyDigest: digest({ + version: review.version, + network: review.network, + required: review.base.required, + total: review.base.total, + signers: review.base.signers, + inheritance: null, + }), + mobileIdentityDigest: mobileIdentity(mobile), + }; +} + +function copy32(value: Uint8Array, code: string): Buffer { + if (!(value instanceof Uint8Array) || value.length !== 32) { + fail(code, 'Expected exactly 32 bytes of secret material'); + } + return Buffer.from(value); +} + +/** Adapter-returned secret bytes are owned here and cleared in finally. */ +function take32(value: Uint8Array, code: string): Buffer { + if (!(value instanceof Uint8Array) || value.length !== 32) { + value?.fill?.(0); + fail(code, 'Expected exactly 32 bytes of secret material'); + } + return Buffer.from(value.buffer, value.byteOffset, value.byteLength); +} + +async function freshBytes(crypto: PreviewBackupFixtureCrypto, length: number): Promise { + const value = await crypto.randomBytes(length); + if (!(value instanceof Uint8Array) || value.length !== length) { + fail('INVALID_RANDOMNESS', 'Invalid cryptographic random byte result'); + } + return Buffer.from(value); +} + +function assertSeedIdentity(seed: Buffer, mobile: RecoverableMobileSigner): void { + const root = bip32.fromSeed(seed, bitcoin.networks.testnet); + if ( + Buffer.from(root.fingerprint).toString('hex').toUpperCase() !== mobile.masterFingerprint || + root.derivePath(RECOVERABLE_MOBILE_KEY_SIGNER_PATH).neutered().toBase58() !== mobile.xpub || + mobile.derivationPath !== RECOVERABLE_MOBILE_KEY_SIGNER_PATH + ) + fail( + 'MOBILE_IDENTITY_MISMATCH', + 'Recovered key does not match the independently held Mobile policy' + ); +} + +function hexBytes(value: unknown, length: number): Buffer { + if (typeof value !== 'string' || !new RegExp(`^[0-9a-f]{${length * 2}}$`).test(value)) { + fail('INVALID_BACKUP_FORMAT', 'Invalid preview backup byte encoding or length'); + } + return Buffer.from(value, 'hex'); +} + +function parseEnvelope(serialized: string): BackupEnvelope { + if ( + typeof serialized !== 'string' || + Buffer.byteLength(serialized, 'utf8') > MAX_ENVELOPE_BYTES + ) { + fail('INVALID_BACKUP_FORMAT', 'Preview backup exceeds the supported record bound'); + } + let envelope: BackupEnvelope; + try { + envelope = JSON.parse(serialized); + } catch { + return fail('INVALID_BACKUP_FORMAT', 'Invalid preview backup JSON'); + } + exactKeys(envelope, ['header', 'ciphertextHex', 'tagHex']); + const { header } = envelope; + exactKeys(header, [ + 'scope', + 'network', + 'backupId', + 'credentialId', + 'version', + 'purpose', + 'policyDigest', + 'mobileIdentityDigest', + 'kdf', + 'cipher', + ]); + exactKeys(header.kdf, ['algorithm', 'iterations', 'saltHex']); + exactKeys(header.cipher, ['algorithm', 'nonceHex', 'tagBytes']); + validateContext({ + scope: header.scope, + network: header.network, + backupId: header.backupId, + credentialId: header.credentialId, + }); + if ( + header.version !== 1 || + header.purpose !== 'preview-mobile-key-local-backup' || + header.kdf.algorithm !== 'pbkdf2-hmac-sha256' || + header.kdf.iterations !== KDF_ITERATIONS || + header.cipher.algorithm !== 'aes-256-gcm' || + header.cipher.tagBytes !== 16 + ) + fail('INVALID_BACKUP_FORMAT', 'Unsupported preview backup version or crypto parameters'); + hexBytes(header.policyDigest, 32); + hexBytes(header.mobileIdentityDigest, 32); + hexBytes(header.kdf.saltHex, 16); + hexBytes(header.cipher.nonceHex, 12); + hexBytes(envelope.ciphertextHex, 32); + hexBytes(envelope.tagHex, 16); + return envelope; +} + +/** AAD has fixed field order, independent of parsed JSON property ordering. */ +function authenticatedHeader(header: BackupHeader): Buffer { + return Buffer.from( + JSON.stringify([ + header.version, + header.purpose, + header.scope, + header.network, + header.backupId, + header.credentialId, + header.policyDigest, + header.mobileIdentityDigest, + header.kdf.algorithm, + header.kdf.iterations, + header.kdf.saltHex, + header.cipher.algorithm, + header.cipher.nonceHex, + header.cipher.tagBytes, + ]), + 'utf8' + ); +} + +/** Caller owns input bytes. Internal byte copies are cleared on every exit. */ +export async function createPreviewMobileKeyBackupFixture( + seed: Uint8Array, + expected: PreviewBackupExpectation, + crypto: PreviewBackupFixtureCrypto = UNAVAILABLE_PREVIEW_BACKUP_CRYPTO +): Promise { + requireFixtureCrypto(crypto); + const binding = expectedBinding(expected); + const seedCopy = copy32(seed, 'INVALID_MOBILE_SEED'); + let secret: Buffer; + let key: Buffer; + try { + secret = copy32(expected.recoverySecret, 'INVALID_RECOVERY_SECRET'); + if (seedCopy.equals(secret)) + fail('RECOVERY_SECRET_REUSES_SEED', 'Recovery secret must be independent of the Mobile Key'); + assertSeedIdentity(seedCopy, binding.mobile); + const salt = await freshBytes(crypto, 16); + const nonce = await freshBytes(crypto, 12); + const header: BackupHeader = { + ...binding.context, + version: 1, + purpose: 'preview-mobile-key-local-backup', + policyDigest: binding.policyDigest, + mobileIdentityDigest: binding.mobileIdentityDigest, + kdf: { + algorithm: 'pbkdf2-hmac-sha256', + iterations: KDF_ITERATIONS, + saltHex: salt.toString('hex'), + }, + cipher: { algorithm: 'aes-256-gcm', nonceHex: nonce.toString('hex'), tagBytes: 16 }, + }; + key = take32(await crypto.deriveKey(secret, salt, KDF_ITERATIONS), 'INVALID_DERIVED_KEY'); + const encrypted = await crypto.encrypt(key, nonce, seedCopy, authenticatedHeader(header)); + const ciphertext = Buffer.from(encrypted.ciphertext); + const tag = Buffer.from(encrypted.tag); + if (ciphertext.length !== 32 || tag.length !== 16) { + fail('INVALID_CRYPTO_OUTPUT', 'Invalid authenticated encryption result'); + } + return JSON.stringify({ + header, + ciphertextHex: ciphertext.toString('hex'), + tagHex: tag.toString('hex'), + }); + } catch (error) { + if (error instanceof PreviewMobileKeyBackupError) throw error; + return fail('BACKUP_CRYPTO_FAILED', 'Preview backup encryption failed'); + } finally { + seedCopy.fill(0); + secret?.fill(0); + key?.fill(0); + } +} + +/** Authenticates and proves exact key identity; never returns/imports the seed. */ +export async function verifyPreviewMobileKeyBackupFixture( + serialized: string, + expected: PreviewBackupExpectation, + crypto: PreviewBackupFixtureCrypto = UNAVAILABLE_PREVIEW_BACKUP_CRYPTO +): Promise { + requireFixtureCrypto(crypto); + const binding = expectedBinding(expected); + const { header, ciphertextHex, tagHex } = parseEnvelope(serialized); + if ( + header.backupId !== binding.context.backupId || + header.credentialId !== binding.context.credentialId || + header.policyDigest !== binding.policyDigest || + header.mobileIdentityDigest !== binding.mobileIdentityDigest + ) + fail( + 'BACKUP_CONTEXT_MISMATCH', + 'Backup does not match the independently held policy and context' + ); + let secret: Buffer; + let key: Buffer; + let plaintext: Buffer; + try { + secret = copy32(expected.recoverySecret, 'INVALID_RECOVERY_SECRET'); + key = take32( + await crypto.deriveKey(secret, hexBytes(header.kdf.saltHex, 16), KDF_ITERATIONS), + 'INVALID_DERIVED_KEY' + ); + plaintext = take32( + await crypto.decrypt( + key, + hexBytes(header.cipher.nonceHex, 12), + hexBytes(ciphertextHex, 32), + hexBytes(tagHex, 16), + authenticatedHeader(header) + ), + 'INVALID_RECOVERED_SEED' + ); + if (plaintext.equals(secret)) { + fail('RECOVERY_SECRET_REUSES_SEED', 'Recovery secret must be independent of the Mobile Key'); + } + assertSeedIdentity(plaintext, binding.mobile); + return { + kind: 'local-fixture-mobile-key-backup-verified', + network: NetworkType.TESTNET, + backupId: binding.context.backupId, + policyDigest: binding.policyDigest, + mobileIdentityDigest: binding.mobileIdentityDigest, + authenticatedEncryptionVerified: true, + exactMobileIdentityMatched: true, + exactFixtureReadbackVerified: false, + cloudBackupVerified: false, + nativeRestoreVerified: false, + walletReady: false, + }; + } catch (error) { + if (error instanceof PreviewMobileKeyBackupError) throw error; + return fail('BACKUP_AUTH_FAILED', 'Backup authentication failed'); + } finally { + secret?.fill(0); + key?.fill(0); + plaintext?.fill(0); + } +} + +/** Local mock only: upload acknowledgement cannot mark a backup healthy. */ +export async function writeAndVerifyPreviewMobileKeyBackupFixture( + seed: Uint8Array, + expected: PreviewBackupExpectation, + transport: PreviewBackupFixtureTransport, + crypto: PreviewBackupFixtureCrypto = UNAVAILABLE_PREVIEW_BACKUP_CRYPTO +): Promise { + if ( + transport?.kind !== 'local-fixture' || + typeof transport.write !== 'function' || + typeof transport.read !== 'function' + ) { + fail('FIXTURE_TRANSPORT_UNAVAILABLE', 'Only a local fixture transport is supported'); + } + const { backupId } = expected.context; + const serialized = await createPreviewMobileKeyBackupFixture(seed, expected, crypto); + let readback: string | null; + try { + await transport.write(backupId, serialized); + readback = await transport.read(backupId); + } catch { + return fail('FIXTURE_READBACK_FAILED', 'Fixture backup write/readback failed'); + } + if (readback !== serialized) { + fail('FIXTURE_READBACK_MISMATCH', 'Fixture readback is missing, stale or different'); + } + const evidence = await verifyPreviewMobileKeyBackupFixture(readback, expected, crypto); + return { ...evidence, exactFixtureReadbackVerified: true }; +} diff --git a/src/services/wallets/recoverable/previewMobileKeyReadback.ts b/src/services/wallets/recoverable/previewMobileKeyReadback.ts index 4a6a9d5a7..2a5c70619 100644 --- a/src/services/wallets/recoverable/previewMobileKeyReadback.ts +++ b/src/services/wallets/recoverable/previewMobileKeyReadback.ts @@ -1,14 +1,21 @@ +import BIP32Factory from 'bip32'; import * as bitcoin from 'bitcoinjs-lib'; import { Buffer } from 'buffer'; import { DeviceMobileKeyError, getOrCreatePreviewDeviceMobileKey, + readExistingPreviewDeviceMobileKey, } from './deviceMobileKey'; +import { SignerType } from '../enums'; +import ecc from '../operations/taproot-utils/noble_ecc'; import type { RecoverableMobileSigner } from './policyDraft'; +const bip32 = BIP32Factory(ecc); + /** * A LOCAL, opt-in diagnostic. It may create the native Preview Mobile Key, - * then reads it a second time. No wallet, server key, funding, backup, signing + * then reads the existing record without permission to create a replacement. + * No wallet, server key, funding, backup, signing * authority, or recovery capability is created or implied. * * This cannot prove continuity across a process restart or reinstall. The @@ -26,40 +33,63 @@ export interface PreviewMobileKeyReadbackEvidence { recoveryVerified: false; } -function isExpectedPreviewSigner( - signer: RecoverableMobileSigner -): signer is RecoverableMobileSigner & { - origin: Extract; +function snapshotExpectedPreviewSigner(signer: RecoverableMobileSigner): { + masterFingerprint: string; + xpub: string; + derivationPath: string; + sourceId: string; } { - return ( + const validShape = signer?.role === 'mobile' && + signer.signerType === SignerType.MOBILE_KEY && signer?.origin?.kind === 'device-generated' && signer.origin.version === 1 && signer.derivationPath === "m/48'/1'/0'/2'" && typeof signer.masterFingerprint === 'string' && /^[A-F0-9]{8}$/.test(signer.masterFingerprint) && typeof signer.xpub === 'string' && - signer.xpub.startsWith('tpub') - ); -} - -export async function checkPreviewMobileKeyReadback( - read: () => Promise = getOrCreatePreviewDeviceMobileKey -): Promise { - const first = await read(); - if (!isExpectedPreviewSigner(first)) { + signer.xpub.length <= 120 && + signer.origin.sourceId === `device-generated:${signer.xpub}` && + Object.keys(signer).every((key) => + ['role', 'signerType', 'origin', 'derivationPath', 'masterFingerprint', 'xpub'].includes(key) + ) && + Object.keys(signer.origin).every((key) => ['kind', 'version', 'sourceId'].includes(key)); + let validAccountKey = false; + if (validShape) { + try { + const node = bip32.fromBase58(signer.xpub, bitcoin.networks.testnet); + validAccountKey = node.isNeutered() && node.depth === 4 && node.index === 0x80000002; + } catch { + validAccountKey = false; + } + } + if (!validShape || !validAccountKey) { throw new DeviceMobileKeyError( 'INVALID_PUBLIC_SIGNER', 'Native Mobile Key returned unexpected public metadata' ); } - const second = await read(); + // Copy values before the next asynchronous call: a mutable reused object + // must not rewrite the first observation and conceal a changed key. + return { + masterFingerprint: signer.masterFingerprint, + xpub: signer.xpub, + derivationPath: signer.derivationPath, + sourceId: (signer.origin as { sourceId: string }).sourceId, + }; +} + +export async function checkPreviewMobileKeyReadback( + read: () => Promise = getOrCreatePreviewDeviceMobileKey, + readExisting: () => Promise = readExistingPreviewDeviceMobileKey +): Promise { + const first = snapshotExpectedPreviewSigner(await read()); + const second = snapshotExpectedPreviewSigner(await readExisting()); if ( - !isExpectedPreviewSigner(second) || first.masterFingerprint !== second.masterFingerprint || first.xpub !== second.xpub || first.derivationPath !== second.derivationPath || - first.origin.sourceId !== second.origin.sourceId + first.sourceId !== second.sourceId ) { throw new DeviceMobileKeyError( 'MOBILE_KEY_CHANGED', diff --git a/tests/native/preview-mobile-key/KeeperPreviewMobileKeyStoreTest.kt b/tests/native/preview-mobile-key/KeeperPreviewMobileKeyStoreTest.kt new file mode 100644 index 000000000..2b321b841 --- /dev/null +++ b/tests/native/preview-mobile-key/KeeperPreviewMobileKeyStoreTest.kt @@ -0,0 +1,394 @@ +package com.hexa_keeper + +import java.io.File +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.nio.file.Files +import java.security.MessageDigest +import java.util.concurrent.Callable +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.SecretKeySpec + +// This compiles the production core. IO/key adapters here are test fixtures, +// not implementations or tests of Android AtomicFile or Android Keystore. +private val fixtureSeed = ByteArray(32) { it.toByte() } + +private fun aesKey(): SecretKey = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + +private fun expectFailure(block: () -> Unit) { + var failed = false + try { + block() + } catch (_: Exception) { + failed = true + } + check(failed) { "Operation unexpectedly succeeded" } +} + +private class FixtureKeys : KeeperPreviewMobileKeyEncryptionKeys { + var key: SecretKey? = null + var aliasPresent = false + var reads = 0 + var creations = 0 + var readError = false + + override fun read(): SecretKey? { + reads++ + if (readError) throw IllegalStateException("Injected Keystore error") + return key + } + + override fun containsAlias() = aliasPresent + + override fun create(): SecretKey { + check(!aliasPresent) + creations++ + return aesKey().also { key = it; aliasPresent = true } + } +} + +private class FixtureRecords(private val files: KeeperPreviewMobileKeyFiles) : KeeperPreviewMobileKeyRecords { + var writes = 0 + var readError = false + var writeError = false + var readOverride: (() -> ByteArray)? = null + + override fun read(): ByteArray { + if (readError) throw IllegalStateException("Injected storage error") + return readOverride?.invoke() ?: files.seedFile.readBytes() + } + + override fun writeDurably(record: ByteArray) { + writes++ + if (writeError) { + File(files.seedFile.path + ".new").writeBytes(record.copyOf(9)) + throw IllegalStateException("Injected interrupted write") + } + files.seedFile.writeBytes(record) + } +} + +private class Fixture : AutoCloseable { + val directory = Files.createTempDirectory("keeper-preview-mobile-key-check-").toFile() + val files = KeeperPreviewMobileKeyFiles(directory) + val keys = FixtureKeys() + val records = FixtureRecords(files) + var randomCalls = 0 + var generatedBuffer: ByteArray? = null + var randomError = false + val store = KeeperPreviewMobileKeyStore(files, records, keys) { buffer -> + randomCalls++ + generatedBuffer = buffer + fixtureSeed.copyInto(buffer) + if (randomError) throw IllegalStateException("Injected random failure") + } + + fun assertNoCreation() { + check(keys.creations == 0 && records.writes == 0 && randomCalls == 0) + } + + fun assertGeneratedCleared() { + check(generatedBuffer?.all { it == 0.toByte() } == true) + } + + override fun close() { check(directory.deleteRecursively()) } +} + +private fun digest(bytes: ByteArray) = MessageDigest.getInstance("SHA-256") + .digest(bytes).joinToString("") { "%02x".format(it) } + +// Cross-process fixtures store a software key in a temporary directory solely +// for this harness; the app still uses the Android Keystore implementation. +private fun processStore(directory: File): KeeperPreviewMobileKeyStore { + val files = KeeperPreviewMobileKeyFiles(directory) + val keyFile = File(directory, "harness-software-key.bin") + val keys = object : KeeperPreviewMobileKeyEncryptionKeys { + override fun read(): SecretKey? = if (keyFile.exists()) { + SecretKeySpec(keyFile.readBytes(), "AES") + } else null + + override fun containsAlias() = keyFile.exists() + + override fun create(): SecretKey = aesKey().also { + keyFile.writeBytes(it.encoded) + File(directory, "harness-key-creations.bin").appendBytes(byteArrayOf(1)) + } + } + return KeeperPreviewMobileKeyStore(files, object : KeeperPreviewMobileKeyRecords { + override fun read() = files.seedFile.readBytes() + override fun writeDurably(record: ByteArray) { files.seedFile.writeBytes(record) } + }, keys) +} + +fun main(args: Array) { + if (args.firstOrNull() == "lock-child") { + val seed = processStore(File(args[1])).getSeed(createIfMissing = true) + try { println(digest(seed)) } finally { seed.fill(0) } + return + } + + var passed = 0 + fun test(name: String, block: () -> Unit) { + block() + passed++ + println("PASS $name") + } + + test("actual AES-GCM codec round trip and randomized nonce") { + val key = aesKey() + val record = KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, key) + check(record.size == 61 && record[0] == 1.toByte()) + check(KeeperPreviewMobileKeyRecord.decrypt(record, key).contentEquals(fixtureSeed)) + check(!record.contentEquals(KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, key))) + } + + test("every record byte mutation fails authentication or version validation") { + val key = aesKey() + val record = KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, key) + for (index in record.indices) { + val mutated = record.copyOf() + mutated[index] = (mutated[index].toInt() xor 1).toByte() + expectFailure { KeeperPreviewMobileKeyRecord.decrypt(mutated, key) } + } + } + + test("wrong encryption key and wrong app authenticated data are rejected") { + val key = aesKey() + val record = KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, key) + expectFailure { KeeperPreviewMobileKeyRecord.decrypt(record, aesKey()) } + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, key) + cipher.updateAAD("io.hexawallet.bitcoinkeeper".toByteArray()) + val wrongAppRecord = byteArrayOf(1) + cipher.iv + cipher.doFinal(fixtureSeed) + expectFailure { KeeperPreviewMobileKeyRecord.decrypt(wrongAppRecord, key) } + } + + test("record and seed length boundaries fail closed") { + val key = aesKey() + val record = KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, key) + for (size in listOf(0, 1, 12, 29, 60, 62, 128)) { + expectFailure { KeeperPreviewMobileKeyRecord.decrypt(record.copyOf(size), key) } + } + for (size in listOf(0, 16, 31, 33, 64)) { + expectFailure { KeeperPreviewMobileKeyRecord.encrypt(ByteArray(size), key) } + } + } + + test("actual native file reader rejects short/oversized records with bounded reads") { + val record = KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, aesKey()) + check(KeeperPreviewMobileKeyRecord.readBounded(ByteArrayInputStream(record)) + .contentEquals(record)) + expectFailure { + KeeperPreviewMobileKeyRecord.readBounded(ByteArrayInputStream(record.copyOf(60))) + } + var consumed = 0 + val endlessCorruption = object : InputStream() { + override fun read(): Int { consumed++; return 1 } + } + expectFailure { KeeperPreviewMobileKeyRecord.readBounded(endlessCorruption) } + check(consumed == 62) { "Corruption caused an unbounded file read" } + } + + test("creation returns durable readback and later reads keep the same identity") { + Fixture().use { f -> + val seed = f.store.getSeed(createIfMissing = true) + check(seed.contentEquals(fixtureSeed)) + check(f.store.getSeed(createIfMissing = false).contentEquals(seed)) + check(f.store.getSeed(createIfMissing = true).contentEquals(seed)) + check(f.keys.creations == 1 && f.records.writes == 1 && f.randomCalls == 1) + check(f.files.seedFile.readBytes().size == 61) + f.assertGeneratedCleared() + seed.fill(0) + } + } + + test("read-existing on empty store touches neither keys nor random generation") { + Fixture().use { f -> + expectFailure { f.store.getSeed(createIfMissing = false) } + f.assertNoCreation() + check(f.keys.reads == 0 && !f.files.hasAnyRecord()) + } + } + + test("alias without any record never creates a replacement seed") { + Fixture().use { f -> + f.keys.key = aesKey() + f.keys.aliasPresent = true + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + } + } + + test("unreadable alias never creates a replacement encryption key") { + Fixture().use { f -> + f.keys.aliasPresent = true + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + } + } + + test("existing seed record without encryption alias is preserved") { + Fixture().use { f -> + val record = KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, aesKey()) + f.files.seedFile.writeBytes(record) + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + check(f.files.seedFile.readBytes().contentEquals(record)) + } + } + + test("lone .new and .bak files are existing-store tombstones") { + for (suffix in listOf(".new", ".bak")) { + Fixture().use { f -> + val tombstone = File(f.files.seedFile.path + suffix) + tombstone.writeBytes(byteArrayOf(7, 8, 9)) + check(f.files.hasAnyRecord()) + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + f.keys.key = aesKey() + f.keys.aliasPresent = true + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + check(tombstone.readBytes().contentEquals(byteArrayOf(7, 8, 9))) + } + } + } + + test("adapter-restored backup is read without creating a new seed") { + Fixture().use { f -> + f.keys.key = aesKey() + f.keys.aliasPresent = true + val backup = File(f.files.seedFile.path + ".bak") + backup.writeBytes(KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, f.keys.key!!)) + f.records.readOverride = { backup.readBytes() } + check(f.store.getSeed(createIfMissing = true).contentEquals(fixtureSeed)) + f.assertNoCreation() + } + } + + test("corrupt stored record is rejected and never rewritten") { + Fixture().use { f -> + f.keys.key = aesKey() + f.keys.aliasPresent = true + val record = KeeperPreviewMobileKeyRecord.encrypt(fixtureSeed, f.keys.key!!) + record[30] = (record[30].toInt() xor 1).toByte() + f.files.seedFile.writeBytes(record) + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + check(f.files.seedFile.readBytes().contentEquals(record)) + } + } + + test("random source failure clears generated seed and exposes nothing") { + Fixture().use { f -> + f.randomError = true + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertGeneratedCleared() + check(f.records.writes == 0) + expectFailure { f.store.getSeed(createIfMissing = true) } + check(f.randomCalls == 1) + } + } + + test("interrupted write clears generated seed and retry cannot replace it") { + Fixture().use { f -> + f.records.writeError = true + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertGeneratedCleared() + check(f.files.hasAnyRecord()) + expectFailure { f.store.getSeed(createIfMissing = true) } + check(f.randomCalls == 1 && f.records.writes == 1 && f.keys.creations == 1) + } + } + + test("authenticated but different readback rejects the generated seed") { + Fixture().use { f -> + f.records.readOverride = { + KeeperPreviewMobileKeyRecord.encrypt(ByteArray(32) { 42 }, f.keys.key!!) + } + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertGeneratedCleared() + check(f.records.writes == 1) + } + } + + test("durable readback IO failure rejects and clears generated seed") { + Fixture().use { f -> + f.records.readError = true + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertGeneratedCleared() + check(f.files.hasAnyRecord()) + expectFailure { f.store.getSeed(createIfMissing = true) } + check(f.randomCalls == 1 && f.records.writes == 1) + } + } + + test("Keystore access error fails before generation or writes") { + Fixture().use { f -> + f.keys.readError = true + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + } + } + + test("missing storage directory fails before key access") { + Fixture().use { f -> + check(f.directory.delete()) + expectFailure { f.store.getSeed(createIfMissing = true) } + f.assertNoCreation() + check(f.keys.reads == 0) + check(f.directory.mkdir()) + } + } + + test("production monitor and file lock serialize concurrent thread creation") { + Fixture().use { f -> + val pool = Executors.newFixedThreadPool(12) + val start = CountDownLatch(1) + try { + val tasks = (1..24).map { + pool.submit(Callable { + start.await() + val seed = f.store.getSeed(createIfMissing = true) + try { digest(seed) } finally { seed.fill(0) } + }) + } + start.countDown() + val identities = tasks.map { it.get(20, TimeUnit.SECONDS) } + check(identities.toSet().size == 1) + check(f.randomCalls == 1 && f.records.writes == 1 && f.keys.creations == 1) + } finally { pool.shutdownNow() } + } + } + + test("production file lock serializes independent JVM processes") { + Fixture().use { f -> + val javaPath = File(System.getProperty("java.home"), "bin/java").path + val classpath = System.getProperty("java.class.path") + val processes = (1..8).map { + ProcessBuilder(javaPath, "-cp", classpath, + "com.hexa_keeper.KeeperPreviewMobileKeyStoreTestKt", "lock-child", f.directory.path) + .redirectErrorStream(true).start() + } + try { + val identities = processes.map { process -> + check(process.waitFor(20, TimeUnit.SECONDS)) { "Child timed out" } + check(process.exitValue() == 0) { "Child failed" } + process.inputStream.bufferedReader().readText().trim().also { + check(it.matches(Regex("[a-f0-9]{64}"))) + } + } + check(identities.toSet().size == 1) + check(File(f.directory, "harness-key-creations.bin").readBytes().size == 1) + check(f.files.seedFile.readBytes().size == 61) + } finally { processes.forEach { it.destroyForcibly() } } + } + } + + println("$passed JVM native-core checks passed; Android/iOS platform services were not exercised.") +} diff --git a/tests/native/preview-mobile-key/README.md b/tests/native/preview-mobile-key/README.md new file mode 100644 index 000000000..4124cd3ed --- /dev/null +++ b/tests/native/preview-mobile-key/README.md @@ -0,0 +1,43 @@ +# Preview Mobile Key native core checks + +Run on Linux with Java 17+, Bash, `curl`, `unzip`, and `sha256sum`: + +```sh +bash tests/native/preview-mobile-key/run.sh +``` + +The harness compiles the app's actual `KeeperPreviewMobileKeyStore.kt` using +Kotlin 2.0.21. It executes 21 checks against real JVM AES-GCM, temporary files, +and the production monitor/file lock. Coverage includes every record-byte +mutation, wrong key/app authenticated data, seed/record length boundaries, +bounded corrupt-file reads, missing/unreadable aliases, `.new`/`.bak` artifacts, +interrupted writes, readback mismatch/failure, clearing the generated seed +buffer, read-existing without creation, and concurrent threads/processes. + +For a narrow Android bridge compilation check against actual Android API 36 +and React Native 0.83.9 classes: + +```sh +bash tests/native/preview-mobile-key/run.sh --android-bridge-typecheck +``` + +Only generated `BuildConfig` is a fixture in that compilation. This is not an +APK build and does not exercise Gradle flavor configuration or app registration. +The runner pins downloaded archives by SHA256. The compiler and React hashes +match publisher checksum files; the Android archive also matched Google's +repository checksum before its SHA256 was recorded. Tool archives stay in the +temporary tools cache; generated check artifacts and fixture directories are +removed after execution. + +These checks use JVM software keys and file adapters. They do not execute +Android Keystore, Android AtomicFile, iOS Keychain/Security, hardware signers, +or a simulator/emulator. The backup-restoration case tests the lifecycle's +response to an adapter-provided record; actual AtomicFile recovery and durability +still require Android validation. Random-source errors are injected; platform +entropy quality and hardware backing are not proved. + +The seed still crosses the native bridge as an immutable base64 string for +preview public-key derivation. Buffer clearing is best effort and cannot erase +all framework/JavaScript copies. Readback proves neither restart durability, +device backup/recovery, non-exportable signing, nor wallet readiness. All +platform and physical-device checks remain required before review approval. diff --git a/tests/native/preview-mobile-key/run.sh b/tests/native/preview-mobile-key/run.sh new file mode 100644 index 000000000..072dfb679 --- /dev/null +++ b/tests/native/preview-mobile-key/run.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -gt 1 || (${1:-} != "" && ${1:-} != "--android-bridge-typecheck") ]]; then + echo "Usage: bash tests/native/preview-mobile-key/run.sh [--android-bridge-typecheck]" >&2 + exit 2 +fi + +test_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +repo_dir=$(cd -- "$test_dir/../../.." && pwd) +tools_dir=${KEEPER_PREVIEW_NATIVE_TOOLS_DIR:-${TMPDIR:-/tmp}/keeper-preview-native-tools} +compiler_version=2.0.21 +compiler_sha256=0352c0a45bd22f80f6b26e485cd04da8047baa5de54865281fb9f89a4a7bcf2a +compiler_archive="$tools_dir/kotlin-compiler-$compiler_version.zip" +mkdir -p -- "$tools_dir" + +if [[ ! -f "$compiler_archive" ]]; then + curl --fail --silent --show-error --location --max-time 180 \ + "https://github.com/JetBrains/kotlin/releases/download/v$compiler_version/kotlin-compiler-$compiler_version.zip" \ + --output "$compiler_archive.download" + mv -- "$compiler_archive.download" "$compiler_archive" +fi +printf '%s %s\n' "$compiler_sha256" "$compiler_archive" | sha256sum --check --status + +# Re-extract the verified archive; do not trust a previously modified compiler binary. +compiler_dir=$(mktemp -d "$tools_dir/compiler.XXXXXXXX") +build_dir=$(mktemp -d "$tools_dir/check.XXXXXXXX") +trap 'rm -rf -- "$compiler_dir" "$build_dir"' EXIT +unzip -q "$compiler_archive" -d "$compiler_dir" +"$compiler_dir/kotlinc/bin/kotlinc" \ + "$repo_dir/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyStore.kt" \ + "$test_dir/KeeperPreviewMobileKeyStoreTest.kt" \ + -jvm-target 17 -include-runtime -d "$build_dir/preview-mobile-key-checks.jar" +java -jar "$build_dir/preview-mobile-key-checks.jar" + +if [[ ${1:-} == "--android-bridge-typecheck" ]]; then + # Actual platform/React classes, plus only the generated build-flag fixture. + # This checks Kotlin bridge types; it does not build an APK or run platform services. + android_archive="$tools_dir/platform-36_r02.zip" + react_archive="$tools_dir/react-android-0.83.9-debug.aar" + if [[ ! -f "$android_archive" ]]; then + curl --fail --silent --show-error --location --max-time 180 \ + https://dl.google.com/android/repository/platform-36_r02.zip \ + --output "$android_archive.download" + mv -- "$android_archive.download" "$android_archive" + fi + if [[ ! -f "$react_archive" ]]; then + curl --fail --silent --show-error --location --max-time 180 \ + https://repo.maven.apache.org/maven2/com/facebook/react/react-android/0.83.9/react-android-0.83.9-debug.aar \ + --output "$react_archive.download" + mv -- "$react_archive.download" "$react_archive" + fi + printf '%s %s\n' \ + 37607369a28c5b640b3a7998868d45898ebcb777565a0e85f9acf36f29631d2e "$android_archive" \ + e8a7e428e5369a541e1eb267b703fb53d84c5be5b2ab32a0d5f8f30dc745e5cc "$react_archive" \ + | sha256sum --check --status + unzip -p "$android_archive" android-36/android.jar > "$build_dir/android.jar" + unzip -p "$react_archive" classes.jar > "$build_dir/react-android.jar" + cat > "$build_dir/BuildConfig.kt" <<'KOTLIN' +package io.hexawallet.keeper +object BuildConfig { const val IS_RECOVERABLE_PREVIEW = true } +KOTLIN + "$compiler_dir/kotlinc/bin/kotlinc" \ + "$repo_dir/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyStore.kt" \ + "$repo_dir/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt" \ + "$build_dir/BuildConfig.kt" \ + -classpath "$build_dir/android.jar:$build_dir/react-android.jar" \ + -jvm-target 17 -d "$build_dir/android-preview-bridge-typecheck.jar" + echo "PASS Android bridge typecheck against API 36 / React Native 0.83.9; not an APK build." +fi diff --git a/tests/preview/recoverableWalletScreen.test.tsx b/tests/preview/recoverableWalletScreen.test.tsx index f3b985898..553f74443 100644 --- a/tests/preview/recoverableWalletScreen.test.tsx +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -5,6 +5,11 @@ import { act, fireEvent, render } from '@testing-library/react-native'; import WalletCreationChooser from '../../src/components/WalletCreationChooser'; import { customTheme } from '../../src/navigation/themes'; import RecoverableWalletPreviewApp from '../../src/preview/recoverable-wallet/RecoverableWalletPreviewApp'; +import { checkPreviewMobileKeyReadback } from 'src/services/wallets/recoverable/previewMobileKeyReadback'; + +jest.mock('src/services/wallets/recoverable/previewMobileKeyReadback', () => ({ + checkPreviewMobileKeyReadback: jest.fn(), +})); jest.mock('src/components/ScreenWrapper', () => { const React = require('react'); @@ -45,6 +50,7 @@ function enterRecoveryOptions(screen) { describe('Recoverable Wallet preview on a small screen', () => { beforeEach(() => { + (checkPreviewMobileKeyReadback as jest.Mock).mockReset(); jest.useFakeTimers(); jest .spyOn(Dimensions, 'get') @@ -57,6 +63,49 @@ describe('Recoverable Wallet preview on a small screen', () => { jest.restoreAllMocks(); }); + test('native key diagnostic is opt-in and never makes the simulated setup functional', async () => { + const screen = render(); + expect(checkPreviewMobileKeyReadback).not.toHaveBeenCalled(); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + finishSimulatedAutomaticSetup(); + expect(checkPreviewMobileKeyReadback).not.toHaveBeenCalled(); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent('SIMULATED'); + fireEvent.press(screen.getByTestId('preview-cancel')); + fireEvent.press(screen.getByTestId('preview-device-mobile-key-entry')); + expect(checkPreviewMobileKeyReadback).not.toHaveBeenCalled(); + (checkPreviewMobileKeyReadback as jest.Mock).mockResolvedValueOnce({ + kind: 'preview-mobile-key-two-read-match', + network: 'testnet', + masterFingerprint: '12345678', + publicIdentityTag: '1234567890ABCDEF', + matchedReads: 2, + backupVerified: false, + walletReady: false, + recoveryVerified: false, + }); + await act(async () => fireEvent.press(screen.getByTestId('primary-Check Key'))); + expect(checkPreviewMobileKeyReadback).toHaveBeenCalledTimes(1); + expect(screen.getByTestId('preview-mobile-key-matched')).toHaveTextContent( + 'Two native reads matched on this device.' + ); + expect(screen.getByTestId('preview-mobile-key-no-backup')).toHaveTextContent('NOT BACKED UP'); + expect(screen.getByTestId('preview-mobile-key-no-backup')).toHaveTextContent( + 'No wallet, signing, cloud recovery or Server Key is active' + ); + }); + + test('native diagnostic failure shows only a safe error code', async () => { + const screen = render(); + fireEvent.press(screen.getByTestId('preview-device-mobile-key-entry')); + (checkPreviewMobileKeyReadback as jest.Mock).mockRejectedValueOnce( + Object.assign(new Error('private diagnostic detail'), { code: 'unsafe secret detail' }) + ); + await act(async () => fireEvent.press(screen.getByTestId('primary-Check Key'))); + expect(screen.getByTestId('preview-mobile-key-failed')).toHaveTextContent('READBACK_FAILED'); + expect(screen.queryByText(/private diagnostic detail/)).toBeNull(); + expect(screen.queryByTestId('preview-mobile-key-matched')).toBeNull(); + }); + test('starts automatic status progress on selection, pauses on cancel, and waits for hardware', () => { const screen = render(); expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('No wallets yet'); diff --git a/tests/services/recoverable/deviceMobileKey.test.ts b/tests/services/recoverable/deviceMobileKey.test.ts index 295e69995..3e1ec66a8 100644 --- a/tests/services/recoverable/deviceMobileKey.test.ts +++ b/tests/services/recoverable/deviceMobileKey.test.ts @@ -1,6 +1,7 @@ import { deriveDeviceMobileKeyPublic, getOrCreatePreviewDeviceMobileKey, + readExistingPreviewDeviceMobileKey, type DeviceMobileKeyAdapters, } from 'src/services/wallets/recoverable/deviceMobileKey'; import NativeConfig from 'react-native-config'; @@ -101,7 +102,7 @@ describe('preview device-generated Mobile Key', () => { } ); - it.each(['not base64', Buffer.alloc(16).toString('base64'), ''])( + it.each(['not base64', Buffer.alloc(16).toString('base64'), '', 'A'.repeat(100_000)])( 'rejects malformed native seed output', async (value) => { await expect(getOrCreatePreviewDeviceMobileKey(adapter(value))).rejects.toMatchObject({ @@ -144,4 +145,70 @@ describe('preview device-generated Mobile Key', () => { release(seed.toString('base64')); expect(await first).toEqual(await second); }); + + it('reloads with the read-only native operation and never requests creation', async () => { + const native = { + ...adapter(), + readExistingSeedBase64: jest.fn(async () => seed.toString('base64')), + }; + expect(await readExistingPreviewDeviceMobileKey(native)).toEqual( + deriveDeviceMobileKeyPublic(seed) + ); + expect(native.readExistingSeedBase64).toHaveBeenCalledTimes(1); + expect(native.getOrCreateSeedBase64).not.toHaveBeenCalled(); + }); + + it('fails closed if a read-only native operation is missing', async () => { + const native = adapter(); + await expect(readExistingPreviewDeviceMobileKey(native)).rejects.toMatchObject({ + code: 'NATIVE_KEY_UNAVAILABLE', + }); + expect(native.getOrCreateSeedBase64).not.toHaveBeenCalled(); + }); + + it('rejects a missing record without falling back to key creation', async () => { + const native = { + ...adapter(), + readExistingSeedBase64: jest.fn(async () => { + throw Object.assign(new Error('Store unavailable'), { + code: 'MOBILE_KEY_STORAGE_UNAVAILABLE', + }); + }), + }; + await expect(readExistingPreviewDeviceMobileKey(native)).rejects.toMatchObject({ + code: 'MOBILE_KEY_STORAGE_UNAVAILABLE', + }); + expect(native.getOrCreateSeedBase64).not.toHaveBeenCalled(); + }); + + it('checks installed identity before read-only access', async () => { + (DeviceInfo.getBundleId as jest.Mock).mockReturnValue('io.hexawallet.bitcoinkeeper'); + const native = { + ...adapter(), + readExistingSeedBase64: jest.fn(async () => seed.toString('base64')), + }; + await expect(readExistingPreviewDeviceMobileKey(native)).rejects.toMatchObject({ + code: 'PREVIEW_ONLY', + }); + expect(native.readExistingSeedBase64).not.toHaveBeenCalled(); + }); + + it('does not substitute an in-flight creation request for a read-only load', async () => { + let release: (value: string) => void = () => undefined; + const native = { + getOrCreateSeedBase64: jest.fn(() => new Promise((resolve) => (release = resolve))), + readExistingSeedBase64: jest.fn(async () => { + throw Object.assign(new Error('Store unavailable'), { + code: 'MOBILE_KEY_STORAGE_UNAVAILABLE', + }); + }), + }; + const creation = getOrCreatePreviewDeviceMobileKey(native); + await expect(readExistingPreviewDeviceMobileKey(native)).rejects.toMatchObject({ + code: 'MOBILE_KEY_STORAGE_UNAVAILABLE', + }); + release(seed.toString('base64')); + await creation; + expect(native.readExistingSeedBase64).toHaveBeenCalledTimes(1); + }); }); diff --git a/tests/services/recoverable/hardwarePublicImport.test.ts b/tests/services/recoverable/hardwarePublicImport.test.ts index abd5378b4..1077a0dd3 100644 --- a/tests/services/recoverable/hardwarePublicImport.test.ts +++ b/tests/services/recoverable/hardwarePublicImport.test.ts @@ -279,4 +279,102 @@ describe('testnet public hardware import', () => { 'INVALID_HARDWARE_EXPORT' ); }); + + test('bounds object string data as well as JSON string input', () => { + const payload = coldcard().payload as Record; + payload.note = 'a'.repeat(128 * 1024); + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload })), + 'INVALID_HARDWARE_EXPORT' + ); + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload: JSON.stringify(payload) })), + 'INVALID_HARDWARE_EXPORT' + ); + }); + + test.each(['unusedXpub', 'note'])('rejects extended private values in %s', (field) => { + const payload = coldcard().payload as Record; + payload[field] = root.derivePath(path).toBase58(); + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload })), + 'PRIVATE_MATERIAL' + ); + }); + + test('rejects inherited hardware fields, hidden private data and accessor payloads', () => { + expectCode( + () => + importRecoverableHardwarePublicData( + coldcard({ + payload: Object.create(coldcard().payload as object), + }) + ), + 'INVALID_HARDWARE_EXPORT' + ); + + const hidden = coldcard().payload as Record; + Object.defineProperty(hidden, 'private_key', { value: 'secret' }); + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload: hidden })), + 'PRIVATE_MATERIAL' + ); + + const getter = jest.fn(() => 'public note'); + const accessor = coldcard().payload as Record; + Object.defineProperty(accessor, 'note', { enumerable: true, get: getter }); + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload: accessor })), + 'INVALID_HARDWARE_EXPORT' + ); + expect(getter).not.toHaveBeenCalled(); + }); + + test('accepts plain null-prototype public exports', () => { + const payload = Object.assign(Object.create(null), coldcard().payload); + expect(importRecoverableHardwarePublicData(coldcard({ payload })).signer.xpub).toBe(tpub); + }); + + test('rejects cycles and excessive nesting in object exports', () => { + const cyclic = coldcard().payload as Record; + cyclic.cycle = cyclic; + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload: cyclic })), + 'INVALID_HARDWARE_EXPORT' + ); + + const nested = coldcard().payload as Record; + let cursor = nested; + for (let depth = 0; depth < 17; depth += 1) { + const child: Record = {}; + cursor.child = child; + cursor = child; + } + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload: nested })), + 'INVALID_HARDWARE_EXPORT' + ); + }); + + test('rejects conflicting nested network claims and non-JSON object values', () => { + expectCode( + () => + importRecoverableHardwarePublicData( + coldcard({ + payload: { + chain: 'XTN', + xfp: fingerprint, + bip48_2: { network: 'mainnet', deriv: path, xpub: tpub }, + }, + }) + ), + 'TESTNET_ONLY' + ); + const payload = coldcard().payload as Record; + payload.note = () => 'not JSON'; + expectCode( + () => importRecoverableHardwarePublicData(coldcard({ payload })), + 'INVALID_HARDWARE_EXPORT' + ); + }); }); diff --git a/tests/services/recoverable/policyDraft.test.ts b/tests/services/recoverable/policyDraft.test.ts index a3167a043..df5678b4d 100644 --- a/tests/services/recoverable/policyDraft.test.ts +++ b/tests/services/recoverable/policyDraft.test.ts @@ -1,5 +1,6 @@ import BIP32Factory from 'bip32'; import * as bitcoin from 'bitcoinjs-lib'; +import bs58check from 'bs58check'; import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; import { NetworkType, SignerType, MultisigScriptType } from 'src/services/wallets/enums'; import { @@ -150,6 +151,14 @@ describe('public Recoverable Wallet policy draft', () => { expect(scheme?.phases[1]).toEqual({ timelock: 85_012, signerCount: 4, required: 2 }); expect(scheme?.miniscript).toBeTruthy(); const { scriptWitnesses } = generateScriptWitnesses(scheme!.policy); + expect(scriptWitnesses.length).toBeGreaterThan(0); + for (const witness of scriptWitnesses) { + // Compiler satisfactions are candidate review data, not Bitcoin consensus + // execution or a hardware signing test. No heir-containing path is early. + const signatures = witness.asm.match(/sig\((?:K[123]|IK1)(?:<\d+;\d+>)?\)/g) || []; + expect(signatures).toHaveLength(2); + if (witness.asm.includes('IK1')) expect(witness.nLockTime).toBe(85_012); + } for (const originalSigner of ['K1', 'K2', 'K3']) { expect( scriptWitnesses.some( @@ -228,6 +237,98 @@ describe('public Recoverable Wallet policy draft', () => { expectCode(() => buildRecoverablePolicyReview(sameXpub), 'DUPLICATE_KEY'); }); + test.each([false, 0, '', [], {}])( + 'rejects malformed explicit inheritance choice %j instead of dropping it', + (inheritanceChoice) => { + expect(() => + buildRecoverablePolicyReview({ + ...input(), + inheritance: inheritanceChoice, + } as any) + ).toThrow(RecoverablePolicyDraftError); + } + ); + + test.each(['m', 'n', 'threshold', 'required'])( + 'rejects an attempt to override fixed quorum using %s', + (field) => { + const draft = input(); + (draft as any)[field] = 1; + expectCode(() => buildRecoverablePolicyReview(draft), 'UNEXPECTED_FIELD'); + } + ); + + test.each([ + 'invented-signer', + SignerType.UNKOWN_SIGNER, + SignerType.POLICY_SERVER, + SignerType.MOBILE_KEY, + ])('rejects unsupported inheritance signer type %s', (signerType) => { + const choice = inheritance(); + choice.signer.signerType = signerType as SignerType; + expectCode( + () => buildRecoverablePolicyReview({ ...input(), inheritance: choice }), + 'INVALID_INHERITANCE_ORIGIN' + ); + }); + + test.each([false, true])( + 'rejects a relabelled account signing key even with changed chain code: %s', + (changeChainCode) => { + const draft = input(); + const encoded = Buffer.from(bs58check.decode(draft.mobile.xpub)); + // BIP32 parent fingerprint and chain code can be relabelled without + // changing the actual serialized account public key at bytes 45–77. + encoded[5] ^= 1; + if (changeChainCode) encoded[13] ^= 1; + draft.hardware.xpub = bs58check.encode(encoded); + expect(draft.hardware.xpub).not.toBe(draft.mobile.xpub); + expect(draft.hardware.masterFingerprint).not.toBe(draft.mobile.masterFingerprint); + expectCode(() => buildRecoverablePolicyReview(draft), 'DUPLICATE_KEY'); + } + ); + + test('rejects a relabelled inheritance signer from an existing role', () => { + const draft = input(); + const heir = inheritance(); + const encoded = Buffer.from(bs58check.decode(draft.server.xpub)); + encoded[5] ^= 1; + heir.signer.xpub = bs58check.encode(encoded); + expectCode( + () => buildRecoverablePolicyReview({ ...draft, inheritance: heir }), + 'DUPLICATE_KEY' + ); + }); + + test('rejects inherited policy fields and accessor data without evaluating it', () => { + const draft = input(); + draft.hardware = Object.create(draft.hardware); + expectCode(() => buildRecoverablePolicyReview(draft), 'INVALID_POLICY_DATA'); + + const getter = jest.fn(() => input().mobile.xpub); + const withAccessor = input(); + Object.defineProperty(withAccessor.mobile, 'xpub', { enumerable: true, get: getter }); + expectCode(() => buildRecoverablePolicyReview(withAccessor), 'INVALID_POLICY_DATA'); + expect(getter).not.toHaveBeenCalled(); + }); + + test('rejects hidden or differently cased private metadata', () => { + const withHiddenSecret = input(); + Object.defineProperty(withHiddenSecret.server, 'private_key', { value: 'secret' }); + expectCode(() => buildRecoverablePolicyReview(withHiddenSecret), 'PRIVATE_MATERIAL'); + + const withCasedSecret = input(); + (withCasedSecret.mobile.origin as any).XPRV = 'secret'; + expectCode(() => buildRecoverablePolicyReview(withCasedSecret), 'PRIVATE_MATERIAL'); + + const withPrivateReference = input(); + withPrivateReference.server.origin.sourceId = bip32 + .fromSeed(Buffer.alloc(32, 8), bitcoin.networks.testnet) + .derivePath(signerPath) + .toBase58(); + expectCode(() => buildRecoverablePolicyReview(withPrivateReference), 'PRIVATE_MATERIAL'); + }); + test('blocks hardware and transport combinations that cannot verify this policy', () => { const tapsigner = input(); tapsigner.hardware.signerType = SignerType.TAPSIGNER; @@ -261,4 +362,28 @@ describe('public Recoverable Wallet policy draft', () => { 'INVALID_ACTIVATION' ); }); + + test.each([ + ['block-height', 500_000_000], + ['median-time-past', 0x100000000], + ['median-time-past', 1_700_000_000], + ])('rejects inheritance %s locktime boundary %s', (kind, value) => { + const choice = inheritance(); + choice.activation.kind = kind as 'block-height' | 'median-time-past'; + choice.activation.value = value as number; + expectCode( + () => buildRecoverablePolicyReview({ ...input(), inheritance: choice }), + 'INVALID_ACTIVATION' + ); + }); + + test('compiles a future median-time-past candidate without enabling funding', () => { + const choice = inheritance(); + choice.activation.kind = 'median-time-past'; + choice.activation.value = 1_700_000_600; + const review = buildRecoverablePolicyReview({ ...input(), inheritance: choice }); + expect(review.candidateMiniscript!.policy).toContain('after(1700000600)'); + expect(review.baseVaultScheme).toBeNull(); + expect(review.fundable).toBe(false); + }); }); diff --git a/tests/services/recoverable/previewMobileKeyBackup.test.ts b/tests/services/recoverable/previewMobileKeyBackup.test.ts new file mode 100644 index 000000000..d8be94d9c --- /dev/null +++ b/tests/services/recoverable/previewMobileKeyBackup.test.ts @@ -0,0 +1,542 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import { Buffer } from 'buffer'; +import { createCipheriv, createDecipheriv, pbkdf2, randomBytes } from 'crypto'; +import { NetworkType, SignerType } from 'src/services/wallets/enums'; +import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; +import { + createPreviewMobileKeyBackupFixture, + verifyPreviewMobileKeyBackupFixture, + writeAndVerifyPreviewMobileKeyBackupFixture, + type PreviewBackupExpectation, + type PreviewBackupFixtureCrypto, + type PreviewBackupFixtureTransport, +} from 'src/services/wallets/recoverable/previewMobileKeyBackup'; + +const bip32 = BIP32Factory(ecc); +const PATH = "m/48'/1'/0'/2'"; +const seed = Buffer.alloc(32, 0x11); +const recoverySecret = Buffer.alloc(32, 0xa3); + +function publicKey(seedBytes: Buffer) { + const root = bip32.fromSeed(seedBytes, bitcoin.networks.testnet); + return { + masterFingerprint: Buffer.from(root.fingerprint).toString('hex').toUpperCase(), + xpub: root.derivePath(PATH).neutered().toBase58(), + derivationPath: PATH, + }; +} + +function expected(): PreviewBackupExpectation { + return { + recoverySecret, + context: { + scope: 'recoverable-preview-local-fixture', + network: NetworkType.TESTNET, + backupId: 'fixture-backup-1', + credentialId: 'fixture-credential-1', + }, + policy: { + version: 1, + network: NetworkType.TESTNET, + mobile: { + role: 'mobile', + signerType: SignerType.MOBILE_KEY, + ...publicKey(seed), + origin: { kind: 'device-generated', version: 1, sourceId: 'fixture-mobile' }, + }, + hardware: { + role: 'hardware', + signerType: SignerType.COLDCARD, + ...publicKey(Buffer.alloc(32, 0x22)), + origin: { + kind: 'hardware-device', + device: SignerType.COLDCARD, + transport: 'qr', + sourceId: 'fixture-hardware', + }, + }, + server: { + role: 'server', + signerType: SignerType.POLICY_SERVER, + ...publicKey(Buffer.alloc(32, 0x33)), + origin: { kind: 'keeper-server-key', sourceId: 'fixture-server-not-enrolled' }, + }, + }, + }; +} + +/** Actual Node/OpenSSL primitives, not mocked encrypt/decrypt or toy crypto. */ +function nodeCrypto(): PreviewBackupFixtureCrypto { + return { + kind: 'local-fixture-crypto', + randomBytes: jest.fn(async (length) => randomBytes(length)), + deriveKey: jest.fn( + (secretBytes, salt, iterations) => + new Promise((resolve, reject) => { + pbkdf2(secretBytes, salt, iterations, 32, 'sha256', (error, key) => { + if (error) reject(error); + else resolve(key); + }); + }) + ), + encrypt: jest.fn(async (key, nonce, plaintext, aad) => { + const cipher = createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 }); + cipher.setAAD(aad); + return { + ciphertext: Buffer.concat([cipher.update(plaintext), cipher.final()]), + tag: cipher.getAuthTag(), + }; + }), + decrypt: jest.fn(async (key, nonce, ciphertext, tag, aad) => { + const decipher = createDecipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 }); + decipher.setAAD(aad); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]); + }), + }; +} + +function mutate(record: string, change: (envelope: any) => void): string { + const envelope = JSON.parse(record); + change(envelope); + return JSON.stringify(envelope); +} + +function changeByte(hex: string): string { + return (hex.startsWith('00') ? '01' : '00') + hex.slice(2); +} + +describe('disconnected preview Mobile Key backup and recovery fixtures', () => { + let serialized: string; + beforeAll(async () => { + serialized = await createPreviewMobileKeyBackupFixture(seed, expected(), nodeCrypto()); + }); + + it('uses real authenticated encryption/KDF and verifies the exact public policy without returning secrets', async () => { + const crypto = nodeCrypto(); + const evidence = await verifyPreviewMobileKeyBackupFixture(serialized, expected(), crypto); + expect(evidence).toMatchObject({ + kind: 'local-fixture-mobile-key-backup-verified', + network: NetworkType.TESTNET, + authenticatedEncryptionVerified: true, + exactMobileIdentityMatched: true, + exactFixtureReadbackVerified: false, + cloudBackupVerified: false, + nativeRestoreVerified: false, + walletReady: false, + }); + expect(evidence.policyDigest).toMatch(/^[0-9a-f]{64}$/); + expect(crypto.deriveKey).toHaveBeenCalledWith( + expect.any(Uint8Array), + expect.any(Uint8Array), + 600_000 + ); + const publicResults = serialized + JSON.stringify(evidence); + for (const secret of [ + seed.toString('hex'), + seed.toString('base64'), + recoverySecret.toString('hex'), + ]) { + expect(publicResults).not.toContain(secret); + } + expect(publicResults).not.toContain(expected().policy.mobile.xpub); + expect(seed).toEqual(Buffer.alloc(32, 0x11)); + expect(recoverySecret).toEqual(Buffer.alloc(32, 0xa3)); + }); + + it('requests fresh salt and nonce on each encryption; identical keys produce different ciphertext', async () => { + const crypto = nodeCrypto(); + const next = await createPreviewMobileKeyBackupFixture(seed, expected(), crypto); + expect(crypto.randomBytes).toHaveBeenNthCalledWith(1, 16); + expect(crypto.randomBytes).toHaveBeenNthCalledWith(2, 12); + const first = JSON.parse(serialized); + const second = JSON.parse(next); + expect(second.header.kdf.saltHex).not.toBe(first.header.kdf.saltHex); + expect(second.header.cipher.nonceHex).not.toBe(first.header.cipher.nonceHex); + expect(second.ciphertextHex).not.toBe(first.ciphertextHex); + expect(second.header.policyDigest).toBe(first.header.policyDigest); + }); + + it.each([ + [ + 'ciphertext', + (envelope) => { + envelope.ciphertextHex = changeByte(envelope.ciphertextHex); + }, + ], + [ + 'tag', + (envelope) => { + envelope.tagHex = changeByte(envelope.tagHex); + }, + ], + [ + 'salt', + (envelope) => { + envelope.header.kdf.saltHex = changeByte(envelope.header.kdf.saltHex); + }, + ], + [ + 'nonce', + (envelope) => { + envelope.header.cipher.nonceHex = changeByte(envelope.header.cipher.nonceHex); + }, + ], + ])('rejects tampered %s under real AES-GCM', async (_, change) => { + await expect( + verifyPreviewMobileKeyBackupFixture(mutate(serialized, change), expected(), nodeCrypto()) + ).rejects.toMatchObject({ code: 'BACKUP_AUTH_FAILED' }); + }); + + it('rejects the wrong independently held recovery secret', async () => { + const wrong = expected(); + wrong.recoverySecret = Buffer.alloc(32, 0xa4); + await expect( + verifyPreviewMobileKeyBackupFixture(serialized, wrong, nodeCrypto()) + ).rejects.toMatchObject({ code: 'BACKUP_AUTH_FAILED' }); + }); + + it.each([ + [ + 'hardware key', + (input: PreviewBackupExpectation) => { + Object.assign(input.policy.hardware, publicKey(Buffer.alloc(32, 0x44))); + }, + ], + [ + 'server key', + (input: PreviewBackupExpectation) => { + Object.assign(input.policy.server, publicKey(Buffer.alloc(32, 0x55))); + }, + ], + [ + 'Mobile key', + (input: PreviewBackupExpectation) => { + Object.assign(input.policy.mobile, publicKey(Buffer.alloc(32, 0x66))); + }, + ], + [ + 'Mobile origin', + (input: PreviewBackupExpectation) => { + input.policy.mobile.origin = { + kind: 'device-generated', + version: 1, + sourceId: 'different-mobile-source', + }; + }, + ], + [ + 'hardware transport', + (input: PreviewBackupExpectation) => { + input.policy.hardware.origin.transport = 'file'; + }, + ], + [ + 'backup ID', + (input: PreviewBackupExpectation) => { + input.context.backupId = 'different-backup'; + }, + ], + [ + 'credential ID', + (input: PreviewBackupExpectation) => { + input.context.credentialId = 'different-credential'; + }, + ], + ])('rejects a record from a different %s before doing KDF work', async (_, change) => { + const wrong = expected(); + change(wrong); + const crypto = nodeCrypto(); + await expect( + verifyPreviewMobileKeyBackupFixture(serialized, wrong, crypto) + ).rejects.toMatchObject({ code: 'BACKUP_CONTEXT_MISMATCH' }); + expect(crypto.deriveKey).not.toHaveBeenCalled(); + }); + + it('authenticates policy/credential headers even when the caller expectation is also relabelled', async () => { + const modified = mutate(serialized, (envelope) => { + envelope.header.credentialId = 'relabelled-credential'; + }); + const relabelled = expected(); + relabelled.context.credentialId = 'relabelled-credential'; + await expect( + verifyPreviewMobileKeyBackupFixture(modified, relabelled, nodeCrypto()) + ).rejects.toMatchObject({ code: 'BACKUP_AUTH_FAILED' }); + }); + + it('rejects an authenticated ciphertext carrying a different seed than the trusted public policy', async () => { + const crypto = nodeCrypto(); + const encrypt = crypto.encrypt; + crypto.encrypt = async (key, nonce, _, aad) => encrypt(key, nonce, Buffer.alloc(32, 0x77), aad); + const wrongSeedRecord = await createPreviewMobileKeyBackupFixture(seed, expected(), crypto); + await expect( + verifyPreviewMobileKeyBackupFixture(wrongSeedRecord, expected(), nodeCrypto()) + ).rejects.toMatchObject({ code: 'MOBILE_IDENTITY_MISMATCH' }); + }); + + it('also rejects externally produced authenticated records that reuse the recovery secret as the seed', async () => { + const crypto = nodeCrypto(); + const encrypt = crypto.encrypt; + crypto.encrypt = async (key, nonce, _, aad) => encrypt(key, nonce, recoverySecret, aad); + const reusedSecretRecord = await createPreviewMobileKeyBackupFixture(seed, expected(), crypto); + await expect( + verifyPreviewMobileKeyBackupFixture(reusedSecretRecord, expected(), nodeCrypto()) + ).rejects.toMatchObject({ code: 'RECOVERY_SECRET_REUSES_SEED' }); + }); + + it.each([ + [ + 'version', + (envelope) => { + envelope.header.version = 2; + }, + ], + [ + 'cipher', + (envelope) => { + envelope.header.cipher.algorithm = 'aes-256-cbc'; + }, + ], + [ + 'KDF algorithm', + (envelope) => { + envelope.header.kdf.algorithm = 'sha256'; + }, + ], + [ + 'too few KDF iterations', + (envelope) => { + envelope.header.kdf.iterations = 1; + }, + ], + [ + 'unbounded KDF iterations', + (envelope) => { + envelope.header.kdf.iterations = 2 ** 53; + }, + ], + [ + 'short ciphertext', + (envelope) => { + envelope.ciphertextHex = '00'; + }, + ], + [ + 'short tag', + (envelope) => { + envelope.tagHex = '00'; + }, + ], + [ + 'noncanonical bytes', + (envelope) => { + envelope.header.kdf.saltHex = 'GG'.repeat(16); + }, + ], + [ + 'extra field', + (envelope) => { + envelope.privateSeed = 'unexpected'; + }, + ], + [ + 'extra header field', + (envelope) => { + envelope.header.walletReady = true; + }, + ], + [ + 'missing field', + (envelope) => { + delete envelope.header.mobileIdentityDigest; + }, + ], + [ + 'null header', + (envelope) => { + envelope.header = null; + }, + ], + [ + 'array KDF', + (envelope) => { + envelope.header.kdf = []; + }, + ], + ])('rejects unsupported %s without attacker-controlled KDF work', async (_, change) => { + const crypto = nodeCrypto(); + await expect( + verifyPreviewMobileKeyBackupFixture(mutate(serialized, change), expected(), crypto) + ).rejects.toMatchObject({ code: 'INVALID_BACKUP_FORMAT' }); + expect(crypto.deriveKey).not.toHaveBeenCalled(); + }); + + it.each(['not-json', '[]', 'null', 'x'.repeat(4097)])( + 'bounds parsing and rejects malformed records', + async (record) => { + const crypto = nodeCrypto(); + await expect( + verifyPreviewMobileKeyBackupFixture(record, expected(), crypto) + ).rejects.toMatchObject({ code: 'INVALID_BACKUP_FORMAT' }); + expect(crypto.deriveKey).not.toHaveBeenCalled(); + } + ); + + it('blocks mainnet, production/cloud contexts and inherited policies', async () => { + const crypto = nodeCrypto(); + const mainnet = expected(); + mainnet.policy.network = NetworkType.MAINNET as never; + await expect(createPreviewMobileKeyBackupFixture(seed, mainnet, crypto)).rejects.toMatchObject({ + code: 'TESTNET_ONLY', + }); + const production = expected(); + production.context.scope = 'production' as never; + await expect( + createPreviewMobileKeyBackupFixture(seed, production, crypto) + ).rejects.toMatchObject({ code: 'TESTNET_FIXTURE_ONLY' }); + const inherited = expected(); + inherited.policy.inheritance = {} as never; + await expect( + createPreviewMobileKeyBackupFixture(seed, inherited, crypto) + ).rejects.toMatchObject({ code: 'INHERITANCE_BACKUP_UNVERIFIED' }); + expect(crypto.randomBytes).not.toHaveBeenCalled(); + }); + + it.each([0, 16, 31, 33, 100000])( + 'requires a bounded 32-byte recovery secret (%s rejected)', + async (length) => { + const input = expected(); + input.recoverySecret = Buffer.alloc(length); + const crypto = nodeCrypto(); + await expect(createPreviewMobileKeyBackupFixture(seed, input, crypto)).rejects.toMatchObject({ + code: 'INVALID_RECOVERY_SECRET', + }); + await expect( + verifyPreviewMobileKeyBackupFixture(serialized, input, crypto) + ).rejects.toMatchObject({ code: 'INVALID_RECOVERY_SECRET' }); + expect(crypto.deriveKey).not.toHaveBeenCalled(); + } + ); + + it('never backs up a mismatched seed or uses the seed itself as its recovery secret', async () => { + const crypto = nodeCrypto(); + await expect( + createPreviewMobileKeyBackupFixture(Buffer.alloc(32, 0x99), expected(), crypto) + ).rejects.toMatchObject({ code: 'MOBILE_IDENTITY_MISMATCH' }); + const input = expected(); + input.recoverySecret = seed; + await expect(createPreviewMobileKeyBackupFixture(seed, input, crypto)).rejects.toMatchObject({ + code: 'RECOVERY_SECRET_REUSES_SEED', + }); + expect(crypto.randomBytes).not.toHaveBeenCalled(); + }); + + it('fails closed with no native crypto adapter or cloud transport', async () => { + await expect(createPreviewMobileKeyBackupFixture(seed, expected())).rejects.toMatchObject({ + code: 'NATIVE_BACKUP_UNAVAILABLE', + }); + await expect(verifyPreviewMobileKeyBackupFixture(serialized, expected())).rejects.toMatchObject( + { code: 'NATIVE_BACKUP_UNAVAILABLE' } + ); + await expect( + writeAndVerifyPreviewMobileKeyBackupFixture( + seed, + expected(), + { kind: 'google-drive' } as never, + nodeCrypto() + ) + ).rejects.toMatchObject({ code: 'FIXTURE_TRANSPORT_UNAVAILABLE' }); + }); + + it('reports fixture readback only after exact write/read match and successful decryption', async () => { + let stored: string | null = null; + const transport: PreviewBackupFixtureTransport = { + kind: 'local-fixture', + write: jest.fn(async (_, record) => { + stored = record; + }), + read: jest.fn(async () => stored), + }; + const evidence = await writeAndVerifyPreviewMobileKeyBackupFixture( + seed, + expected(), + transport, + nodeCrypto() + ); + expect(transport.read).toHaveBeenCalledWith('fixture-backup-1'); + expect(evidence.exactFixtureReadbackVerified).toBe(true); + expect(evidence.cloudBackupVerified).toBe(false); + expect(evidence.nativeRestoreVerified).toBe(false); + }); + + it.each(['missing', 'stale', 'modified', 'unreadable'])( + 'does not treat a successful write with %s readback as healthy', + async (scenario) => { + let stored: string; + const transport: PreviewBackupFixtureTransport = { + kind: 'local-fixture', + write: jest.fn(async (_, record) => { + stored = record; + }), + read: jest.fn(async () => { + if (scenario === 'unreadable') throw new Error('transport failure'); + if (scenario === 'missing') return null; + if (scenario === 'stale') return serialized; + return mutate(stored, (envelope) => { + envelope.tagHex = changeByte(envelope.tagHex); + }); + }), + }; + const crypto = nodeCrypto(); + await expect( + writeAndVerifyPreviewMobileKeyBackupFixture(seed, expected(), transport, crypto) + ).rejects.toMatchObject({ + code: scenario === 'unreadable' ? 'FIXTURE_READBACK_FAILED' : 'FIXTURE_READBACK_MISMATCH', + }); + expect(transport.write).toHaveBeenCalledTimes(1); + expect(crypto.decrypt).not.toHaveBeenCalled(); + } + ); + + it('clears service-owned secret/key/plaintext bytes while retaining caller-owned inputs', async () => { + const crypto = nodeCrypto(); + let derived: Uint8Array; + let decrypted: Uint8Array; + const derive = crypto.deriveKey; + const decrypt = crypto.decrypt; + crypto.deriveKey = jest.fn(async (...args) => { + derived = await derive(...args); + return derived; + }); + crypto.decrypt = jest.fn(async (...args) => { + decrypted = await decrypt(...args); + return decrypted; + }); + await verifyPreviewMobileKeyBackupFixture(serialized, expected(), crypto); + expect(Buffer.from(derived)).toEqual(Buffer.alloc(32)); + expect(Buffer.from(decrypted)).toEqual(Buffer.alloc(32)); + expect(Buffer.from((crypto.deriveKey as jest.Mock).mock.calls[0][0])).toEqual(Buffer.alloc(32)); + expect(recoverySecret).toEqual(Buffer.alloc(32, 0xa3)); + }); + + it('clears derived keys and redacts adapter error messages on failed authentication', async () => { + const crypto = nodeCrypto(); + let derived: Uint8Array; + const derive = crypto.deriveKey; + crypto.deriveKey = async (...args) => { + derived = await derive(...args); + return derived; + }; + crypto.decrypt = async () => { + throw new Error('sensitive adapter detail'); + }; + await expect( + verifyPreviewMobileKeyBackupFixture(serialized, expected(), crypto) + ).rejects.toMatchObject({ + code: 'BACKUP_AUTH_FAILED', + message: 'Backup authentication failed', + }); + expect(Buffer.from(derived)).toEqual(Buffer.alloc(32)); + }); +}); diff --git a/tests/services/recoverable/previewMobileKeyReadback.test.ts b/tests/services/recoverable/previewMobileKeyReadback.test.ts index 2185d9c2f..ab0100e92 100644 --- a/tests/services/recoverable/previewMobileKeyReadback.test.ts +++ b/tests/services/recoverable/previewMobileKeyReadback.test.ts @@ -4,6 +4,9 @@ import { DeviceMobileKeyError, } from 'src/services/wallets/recoverable/deviceMobileKey'; import { checkPreviewMobileKeyReadback } from 'src/services/wallets/recoverable/previewMobileKeyReadback'; +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; jest.mock('react-native-config', () => ({ __esModule: true, @@ -23,7 +26,7 @@ describe('testnet Preview local Mobile Key readback evidence', () => { test('requires two actual public signer reads and returns no secret or full xpub', async () => { const read = jest.fn(async () => mobile); - const evidence = await checkPreviewMobileKeyReadback(read); + const evidence = await checkPreviewMobileKeyReadback(read, read); expect(read).toHaveBeenCalledTimes(2); expect(evidence).toMatchObject({ kind: 'preview-mobile-key-two-read-match', @@ -42,14 +45,20 @@ describe('testnet Preview local Mobile Key readback evidence', () => { }); test('same public identity produces same display tag on repeated verification', async () => { - const a = await checkPreviewMobileKeyReadback(async () => mobile); - const b = await checkPreviewMobileKeyReadback(async () => mobile); + const a = await checkPreviewMobileKeyReadback( + async () => mobile, + async () => mobile + ); + const b = await checkPreviewMobileKeyReadback( + async () => mobile, + async () => mobile + ); expect(a).toEqual(b); }); test('rejects changed native Mobile Key even when same origin shape is returned', async () => { const read = jest.fn().mockResolvedValueOnce(mobile).mockResolvedValueOnce(other); - await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + await expect(checkPreviewMobileKeyReadback(read, read)).rejects.toMatchObject({ code: 'MOBILE_KEY_CHANGED', }); }); @@ -59,7 +68,7 @@ describe('testnet Preview local Mobile Key readback evidence', () => { .fn() .mockResolvedValueOnce(mobile) .mockResolvedValueOnce({ ...other, masterFingerprint: mobile.masterFingerprint }); - await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + await expect(checkPreviewMobileKeyReadback(read, read)).rejects.toMatchObject({ code: 'MOBILE_KEY_CHANGED', }); }); @@ -75,7 +84,7 @@ describe('testnet Preview local Mobile Key readback evidence', () => { bip85Path: "m/83696968'/39'/0'/12'/1000000'", }, })) as never; - await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + await expect(checkPreviewMobileKeyReadback(read, read)).rejects.toMatchObject({ code: 'INVALID_PUBLIC_SIGNER', }); }); @@ -84,9 +93,68 @@ describe('testnet Preview local Mobile Key readback evidence', () => { const read = jest.fn(async () => { throw new DeviceMobileKeyError('MOBILE_KEY_STORAGE_UNAVAILABLE', 'Store unavailable'); }); - await expect(checkPreviewMobileKeyReadback(read)).rejects.toMatchObject({ + await expect(checkPreviewMobileKeyReadback(read, read)).rejects.toMatchObject({ code: 'MOBILE_KEY_STORAGE_UNAVAILABLE', }); expect(read).toHaveBeenCalledTimes(1); }); + + test('uses a separate read-only reload after the first successful create/load', async () => { + const create = jest.fn(async () => mobile); + const reload = jest.fn(async () => mobile); + await checkPreviewMobileKeyReadback(create, reload); + expect(create).toHaveBeenCalledTimes(1); + expect(reload).toHaveBeenCalledTimes(1); + }); + + test('a missing reload record cannot be replaced by another creation call', async () => { + const create = jest.fn(async () => mobile); + const reload = jest.fn(async () => { + throw new DeviceMobileKeyError('MOBILE_KEY_STORAGE_UNAVAILABLE', 'Store unavailable'); + }); + await expect(checkPreviewMobileKeyReadback(create, reload)).rejects.toMatchObject({ + code: 'MOBILE_KEY_STORAGE_UNAVAILABLE', + }); + expect(create).toHaveBeenCalledTimes(1); + }); + + test('snapshots the first read before a native adapter mutates a shared signer object', async () => { + const shared = { ...mobile, origin: { ...mobile.origin } }; + await expect( + checkPreviewMobileKeyReadback( + async () => shared, + async () => { + Object.assign(shared, other); + return shared; + } + ) + ).rejects.toMatchObject({ code: 'MOBILE_KEY_CHANGED' }); + }); + + test.each([ + { xpub: 'tpub-invalid' }, + { signerType: 'POLICY_SERVER' }, + { seed: firstSeed.toString('base64') }, + { origin: { ...mobile.origin, sourceId: 'another-device' } }, + ])('rejects malformed or secret-bearing public metadata', async (overrides) => { + const read = jest.fn(async () => ({ ...mobile, ...overrides })) as never; + await expect(checkPreviewMobileKeyReadback(read, read)).rejects.toMatchObject({ + code: 'INVALID_PUBLIC_SIGNER', + }); + }); + + test('does not accept a valid testnet root xpub as an account-level key', async () => { + const xpub = BIP32Factory(ecc) + .fromSeed(firstSeed, bitcoin.networks.testnet) + .neutered() + .toBase58(); + const read = jest.fn(async () => ({ + ...mobile, + xpub, + origin: { kind: 'device-generated', version: 1, sourceId: `device-generated:${xpub}` }, + })) as never; + await expect(checkPreviewMobileKeyReadback(read, read)).rejects.toMatchObject({ + code: 'INVALID_PUBLIC_SIGNER', + }); + }); }); diff --git a/tests/services/recoverable/testnetScriptVector.test.ts b/tests/services/recoverable/testnetScriptVector.test.ts index c7d239606..fef26d96d 100644 --- a/tests/services/recoverable/testnetScriptVector.test.ts +++ b/tests/services/recoverable/testnetScriptVector.test.ts @@ -1,5 +1,6 @@ import BIP32Factory from 'bip32'; import * as bitcoin from 'bitcoinjs-lib'; +import bs58check from 'bs58check'; import { Buffer } from 'buffer'; import { NetworkType, SignerType } from 'src/services/wallets/enums'; import ecc from 'src/services/wallets/operations/taproot-utils/noble_ecc'; @@ -51,6 +52,75 @@ function fixture(): RecoverablePolicyDraftInput { }; } +function signingKeys(internal = false, index = 0) { + return [1, 2, 3].map((byte) => + bip32 + .fromSeed(Buffer.alloc(32, byte), bitcoin.networks.testnet) + .derivePath(PATH) + .derive(internal ? 1 : 0) + .derive(index) + ); +} + +function syntheticPsbt(internal = false, index = 0) { + const keys = signingKeys(internal, index); + const vector = deriveRecoverableTestnetScriptVector(fixture(), internal, index); + const destination = bitcoin.payments.p2wpkh({ + pubkey: Buffer.from(keys[0].publicKey), + network: bitcoin.networks.testnet, + }).address!; + const psbt = new bitcoin.Psbt({ network: bitcoin.networks.testnet }) + .addInput({ + hash: '11'.repeat(32), + index: 0, + witnessUtxo: { script: vector.scriptPubKey, value: 100_000 }, + witnessScript: vector.witnessScript, + }) + .addOutput({ address: destination, value: 99_000 }); + return { keys, vector, psbt }; +} + +/** + * Independently verify ordered CHECKMULTISIG ECDSA witnesses against the final + * transaction hash and spent amount. BitcoinJS finalization alone does not + * validate signatures and is never sufficient signing proof. + */ +function verifySyntheticWitness( + tx: bitcoin.Transaction, + witnessScript: Buffer, + spentValue = 100_000 +): boolean { + try { + const chunks = bitcoin.script.decompile(witnessScript)!; + if ( + chunks?.length !== 6 || + chunks[0] !== bitcoin.opcodes.OP_2 || + chunks[4] !== bitcoin.opcodes.OP_3 || + chunks[5] !== bitcoin.opcodes.OP_CHECKMULTISIG + ) + return false; + const pubkeys = chunks.slice(1, 4) as Buffer[]; + if (!pubkeys.every(Buffer.isBuffer)) return false; + const witness = tx.ins[0].witness; + if (witness.length !== 4 || witness[0].length !== 0 || !witness[3].equals(witnessScript)) + return false; + let keyIndex = 0; + for (const encoded of witness.slice(1, 3)) { + const { signature, hashType } = bitcoin.script.signature.decode(encoded); + if (hashType !== bitcoin.Transaction.SIGHASH_ALL) return false; + const digest = tx.hashForWitnessV0(0, witnessScript, spentValue, hashType); + while (keyIndex < pubkeys.length && !ecc.verify(digest, pubkeys[keyIndex], signature)) { + keyIndex += 1; + } + if (keyIndex === pubkeys.length) return false; + keyIndex += 1; + } + return true; + } catch (_) { + return false; + } +} + describe('Assisted Multisig offline testnet script and signing vectors', () => { test('matches Keeper existing multisig testnet descriptor and receive-address oracle', () => { // This known public-only descriptor/address is already exercised by @@ -75,7 +145,9 @@ describe('Assisted Multisig offline testnet script and signing vectors', () => { ); expect(result.kind).toBe('unfundable-testnet-2-of-3-vector'); expect(result.fundable).toBe(false); - expect(result.scriptPubKey).toEqual(bitcoin.address.toOutputScript(result.referenceAddress, bitcoin.networks.testnet)); + expect(result.scriptPubKey).toEqual( + bitcoin.address.toOutputScript(result.referenceAddress, bitcoin.networks.testnet) + ); }); test('separates receive/change branches and never produces a mainnet address', () => { @@ -91,17 +163,14 @@ describe('Assisted Multisig offline testnet script and signing vectors', () => { expect(a.fundable).toBe(false); }); - test.each([ - [-1], - [1.25], - [1001], - [Number.NaN], - [Number.POSITIVE_INFINITY], - ])('fails closed for unsupported derivation index %s', (index) => { - expect(() => deriveRecoverableTestnetScriptVector(fixture(), false, index)).toThrow( - RecoverablePolicyDraftError - ); - }); + test.each([[-1], [1.25], [1001], [Number.NaN], [Number.POSITIVE_INFINITY]])( + 'fails closed for unsupported derivation index %s', + (index) => { + expect(() => deriveRecoverableTestnetScriptVector(fixture(), false, index)).toThrow( + RecoverablePolicyDraftError + ); + } + ); test('rejects a nonboolean branch selector and the mainnet network', () => { expect(() => deriveRecoverableTestnetScriptVector(fixture(), 'false' as never, 0)).toThrow( @@ -122,6 +191,16 @@ describe('Assisted Multisig offline testnet script and signing vectors', () => { ); }); + test('rejects relabelled duplicate account keys before script derivation', () => { + const input = fixture(); + const encoded = Buffer.from(bs58check.decode(input.mobile.xpub)); + encoded[5] ^= 1; + input.hardware.xpub = bs58check.encode(encoded); + expect(() => deriveRecoverableTestnetScriptVector(input, false, 0)).toThrow( + /independent key material/ + ); + }); + test('does not reuse the base-2-of-3 script for an inheritance wallet', () => { const input = fixture(); input.inheritance = { @@ -150,37 +229,108 @@ describe('Assisted Multisig offline testnet script and signing vectors', () => { ])('a real BitcoinJS PSBT can be finalized by %s without the third signer', (_, pair) => { // Test-only deterministic private keys and a synthetic UTXO: this proves // script/signature satisfaction, NOT network broadcast or server enrollment. - const keys = [1, 2, 3].map((byte) => - bip32.fromSeed(Buffer.alloc(32, byte), bitcoin.networks.testnet) - .derivePath(PATH).derive(0).derive(0) - ); - const vector = deriveRecoverableTestnetScriptVector(fixture(), false, 0); - const makePsbt = () => { - const destination = bitcoin.payments.p2wpkh({ - pubkey: Buffer.from(keys[0].publicKey), - network: bitcoin.networks.testnet, - }).address!; - return new bitcoin.Psbt({ network: bitcoin.networks.testnet }) - .addInput({ - hash: '11'.repeat(32), - index: 0, - witnessUtxo: { script: vector.scriptPubKey, value: 100_000 }, - witnessScript: vector.witnessScript, - }) - .addOutput({ address: destination, value: 99_000 }); - }; + for (const [internal, index] of [ + [false, 0], + [true, 0], + [false, 1000], + ] as const) { + const { keys, vector, psbt: insufficient } = syntheticPsbt(internal, index); + insufficient.signInput(0, keys[pair[0]]); + expect(() => insufficient.finalizeAllInputs()).toThrow(); + + const { psbt: complete } = syntheticPsbt(internal, index); + complete.signInput(0, keys[pair[0]]); + complete.signInput(0, keys[pair[1]]); + expect( + complete.validateSignaturesOfAllInputs((pubkey, hash, signature) => + ecc.verify(hash, pubkey, signature) + ) + ).toBe(true); + complete.finalizeAllInputs(); + const tx = complete.extractTransaction(); + expect(tx.ins[0].witness).toHaveLength(4); + expect(tx.ins[0].witness[0]).toHaveLength(0); + expect(tx.ins[0].witness[3]).toEqual(vector.witnessScript); + expect(verifySyntheticWitness(tx, vector.witnessScript)).toBe(true); + } + }); + + test('BIP67 sorts actual child public keys and P2WSH commits to the whole witness script', () => { + for (const [internal, index] of [ + [false, 0], + [true, 0], + [false, 1000], + ] as const) { + const { keys, vector } = syntheticPsbt(internal, index); + const expectedKeys = keys.map((key) => Buffer.from(key.publicKey)).sort(Buffer.compare); + expect(bitcoin.script.decompile(vector.witnessScript)).toEqual([ + bitcoin.opcodes.OP_2, + ...expectedKeys, + bitcoin.opcodes.OP_3, + bitcoin.opcodes.OP_CHECKMULTISIG, + ]); + expect(vector.scriptPubKey).toEqual( + Buffer.concat([ + Buffer.from([bitcoin.opcodes.OP_0, 32]), + bitcoin.crypto.sha256(vector.witnessScript), + ]) + ); + } + }); + + test('rejects unrelated keys and keys from a different receive/change derivation', () => { + const { psbt } = syntheticPsbt(); + const outsider = bip32 + .fromSeed(Buffer.alloc(32, 9), bitcoin.networks.testnet) + .derivePath(PATH) + .derive(0) + .derive(0); + for (const wrongKey of [outsider, signingKeys(true)[0], signingKeys(false, 1)[0]]) { + expect(() => psbt.signInput(0, wrongKey)).toThrow(); + } + expect(() => psbt.finalizeAllInputs()).toThrow(); + }); + + test('detects tampered signatures even when the PSBT can be finalized', () => { + const { keys, vector, psbt } = syntheticPsbt(); + psbt.signInput(0, keys[0]); + psbt.signInput(0, keys[1]); + const partial = psbt.data.inputs[0].partialSig![0]; + const decoded = bitcoin.script.signature.decode(partial.signature); + decoded.signature[0] ^= 1; + partial.signature = bitcoin.script.signature.encode(decoded.signature, decoded.hashType); + expect( + psbt.validateSignaturesOfAllInputs((pubkey, hash, signature) => + ecc.verify(hash, pubkey, signature) + ) + ).toBe(false); + psbt.finalizeAllInputs(); + expect(verifySyntheticWitness(psbt.extractTransaction(), vector.witnessScript)).toBe(false); + }); + + test('binds valid signatures to the exact input, outputs, amount and witness order', () => { + const { keys, vector, psbt } = syntheticPsbt(); + psbt.signInput(0, keys[0]); + psbt.signInput(0, keys[1]); + psbt.finalizeAllInputs(); + const tx = psbt.extractTransaction(); + expect(verifySyntheticWitness(tx, vector.witnessScript)).toBe(true); + expect(verifySyntheticWitness(tx, vector.witnessScript, 100_001)).toBe(false); - const insufficient = makePsbt(); - insufficient.signInput(0, keys[pair[0]]); - expect(() => insufficient.finalizeAllInputs()).toThrow(); - - const complete = makePsbt(); - complete.signInput(0, keys[pair[0]]); - complete.signInput(0, keys[pair[1]]); - complete.finalizeAllInputs(); - const witness = complete.extractTransaction().ins[0].witness; - expect(witness).toHaveLength(4); // empty CHECKMULTISIG item + two sigs + witnessScript - expect(witness[0]).toHaveLength(0); - expect(witness[3]).toEqual(vector.witnessScript); + const changedOutput = tx.clone(); + changedOutput.outs[0].value -= 1; + expect(verifySyntheticWitness(changedOutput, vector.witnessScript)).toBe(false); + const changedInput = tx.clone(); + changedInput.ins[0].index += 1; + expect(verifySyntheticWitness(changedInput, vector.witnessScript)).toBe(false); + const swapped = bitcoin.Transaction.fromBuffer(tx.toBuffer()); + [swapped.ins[0].witness[1], swapped.ins[0].witness[2]] = [ + swapped.ins[0].witness[2], + swapped.ins[0].witness[1], + ]; + expect(verifySyntheticWitness(swapped, vector.witnessScript)).toBe(false); + const repeated = bitcoin.Transaction.fromBuffer(tx.toBuffer()); + repeated.ins[0].witness[2] = Buffer.from(repeated.ins[0].witness[1]); + expect(verifySyntheticWitness(repeated, vector.witnessScript)).toBe(false); }); });