diff --git a/.env.recoverable-preview b/.env.recoverable-preview new file mode 100644 index 0000000000..378d6b3637 --- /dev/null +++ b/.env.recoverable-preview @@ -0,0 +1,11 @@ +# 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/ +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/.github/workflows/recoverable-preview-checks.yml b/.github/workflows/recoverable-preview-checks.yml new file mode 100644 index 0000000000..b68d0fbc6d --- /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/.gitignore b/.gitignore index 8c156fac73..5e8a48fd28 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/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..7e3d9609c2 --- /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/App.tsx b/App.tsx index ccf9d5b843..73bdece345 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 0000000000..ccf9d5b843 --- /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 e8ead00b0a..660937035d 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 594604506c..fdb0c092e5 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 0000000000..792d47e898 --- /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 de838aa93e..97a628e4f1 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/KeeperPreviewMobileKeyModule.kt b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt new file mode 100644 index 0000000000..11544e211e --- /dev/null +++ b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyModule.kt @@ -0,0 +1,105 @@ +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.security.KeyStore +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +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) { + 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 { + 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. + promise.reject("MOBILE_KEY_STORAGE_UNAVAILABLE", "Mobile Key secure storage is unavailable") + } + } + + 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) } } + + 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") + } + + override fun containsAlias() = keyStore.containsAlias(KEY_ALIAS) + + 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() + } + } + + private companion object { + const val PREVIEW_PACKAGE = KeeperPreviewMobileKeyRecord.PREVIEW_PACKAGE + const val KEY_ALIAS = "$PREVIEW_PACKAGE.mobile-key.v1" + } +} 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 0000000000..1078a1c61a --- /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/KeeperPreviewMobileKeyStore.kt b/android/app/src/main/java/com/hexa_keeper/KeeperPreviewMobileKeyStore.kt new file mode 100644 index 0000000000..1c2d7dadd0 --- /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/android/app/src/main/java/com/hexa_keeper/MainApplication.kt b/android/app/src/main/java/com/hexa_keeper/MainApplication.kt index 553fc3dc30..024ba75f75 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; @@ -28,7 +29,9 @@ 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(KeeperPreviewMobileKeyPackage()) + else add(CloudBackupPackage()) } override fun getJSMainModuleName(): String = "index" @@ -60,4 +63,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 0000000000..792d47e898 --- /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 0000000000..230c36e116 --- /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 0000000000..709a54110f --- /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 0000000000..b2071c9070 --- /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 new file mode 100644 index 0000000000..ed39085662 --- /dev/null +++ b/docs/preview/recoverable-wallet/README.md @@ -0,0 +1,98 @@ +# Recoverable Wallet — parallel Keeper preview + +**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, 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. + +## Current engineering checkpoint + +| 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. | + +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. + +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. + +`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. + +## Verification and local acceptance + +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. + +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. + +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. + +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 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) + +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 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 + +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**: 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. +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. + +## 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. +- 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. +- **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 + +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 0000000000..7c29003aa1 --- /dev/null +++ b/docs/preview/recoverable-wallet/native-preview.md @@ -0,0 +1,61 @@ +# Native preview packaging (milestone 1) + +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 | +| --- | --- | --- | --- | +| 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. + +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 + +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. + +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. + +## 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 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. + +## 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 new file mode 100644 index 0000000000..33fdf549b0 --- /dev/null +++ b/docs/preview/recoverable-wallet/policy-draft.md @@ -0,0 +1,17 @@ +# 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 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, 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. + +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. + +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/docs/preview/recoverable-wallet/recovery-contact.md b/docs/preview/recoverable-wallet/recovery-contact.md new file mode 100644 index 0000000000..792979df5c --- /dev/null +++ b/docs/preview/recoverable-wallet/recovery-contact.md @@ -0,0 +1,35 @@ +# 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 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. + +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. + +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 + +- 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 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. diff --git a/index.js b/index.js index e352be378e..b7d8025f29 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 b0e96375f5..db11d274af 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 7f0b8da754..b1ce12369f 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 = ( @@ -350,6 +361,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 +478,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; @@ -664,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 */, @@ -994,6 +1025,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 +1873,8 @@ buildConfigurations = ( 83CBBA201A601CBA00E9B192 /* Debug */, 83CBBA211A601CBA00E9B192 /* Release */, + 568042B9DFD49689BEBBFD5A /* RecoverablePreviewDebug */, + 64DC3D260A07EFC1B05F5853 /* RecoverablePreviewRelease */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1433,6 +1884,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 0000000000..5f93a9f78b --- /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 2e26ca1a97..224086a40b 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 0000000000..85d0a4dfe5 --- /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 0000000000..0c67376eba --- /dev/null +++ b/ios/hexa_keeper_recoverable_preview.entitlements @@ -0,0 +1,5 @@ + + + + + diff --git a/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m b/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m new file mode 100644 index 0000000000..3a8b239192 --- /dev/null +++ b/ios/recoverablePreviewMobileKey/KeeperPreviewMobileKey.m @@ -0,0 +1,142 @@ +#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 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); + if (status != errSecSuccess) { + if (result != NULL) CFRelease(result); + return status; + } + if (result == NULL || CFGetTypeID(result) != CFDataGetTypeID()) { + if (result != NULL) CFRelease(result); + return errSecDecode; + } + 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 + +RCT_EXPORT_MODULE(KeeperPreviewMobileKey); + ++ (BOOL)requiresMainQueueSetup +{ + return NO; +} + +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] || + ![[bundle objectForInfoDictionaryKey:@"KeeperRecoverablePreview"] isEqual:@YES]) { + reject(@"PREVIEW_ONLY", @"Mobile Key requires the testnet preview app", nil); + return; + } + + @synchronized([KeeperPreviewMobileKey class]) { + NSMutableData *stored = nil; + OSStatus status = KeeperPreviewReadSeed(&stored); + if (status == errSecSuccess) { + NSString *encoded = [stored base64EncodedStringWithOptions:0]; + KeeperPreviewClearSeed(stored); + resolve(encoded); + return; + } + 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; + } + + 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) { + KeeperPreviewClearSeed(created); + reject(@"MOBILE_KEY_STORAGE_UNAVAILABLE", @"Mobile Key secure storage is unavailable", nil); + return; + } + + NSMutableData *readback = nil; + OSStatus readStatus = KeeperPreviewReadSeed(&readback); + if (readStatus != errSecSuccess || + (status == errSecSuccess && ![readback isEqualToData:created])) { + 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. + NSString *encoded = [readback base64EncodedStringWithOptions:0]; + KeeperPreviewClearSeed(readback); + KeeperPreviewClearSeed(created); + resolve(encoded); + } +} + +@end + +#endif diff --git a/package.json b/package.json index d192ee46fa..62dff2f1b0 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/components/WalletCreationChooser.tsx b/src/components/WalletCreationChooser.tsx new file mode 100644 index 0000000000..245643ba99 --- /dev/null +++ b/src/components/WalletCreationChooser.tsx @@ -0,0 +1,228 @@ +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; + highlighted?: boolean; + testID: string; + onPress: () => void; +}; + +export type WalletCreationChooserProps = { + onSimpleWallet: () => void; + onSeedlessWallet?: () => void; + onAdvancedWallet: () => void; + onImportWallet?: () => void; + showSeedless?: boolean; + 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, + 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} + + + ); +} + +export default function WalletCreationChooser({ + onSimpleWallet, + onSeedlessWallet, + onAdvancedWallet, + onImportWallet, + showSeedless = false, + 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 ( + + + {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 }, + 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 }, + previewNotice: { fontSize: 13, lineHeight: 20, textAlign: 'center' }, +}); diff --git a/src/navigation/Navigator.tsx b/src/navigation/Navigator.tsx index d5ecfc5bbc..81cdfa6428 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 3f71fa0806..e4ffb5ab10 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: { 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 new file mode 100644 index 0000000000..4cafd0bea4 --- /dev/null +++ b/src/preview/recoverable-wallet/RecoverableWalletPreviewApp.tsx @@ -0,0 +1,1307 @@ +import React, { useEffect, useRef, useState } from 'react'; +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'; +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 { + checkPreviewMobileKeyReadback, + type PreviewMobileKeyReadbackEvidence, +} from 'src/services/wallets/recoverable/previewMobileKeyReadback'; +import { + ContactDecisionState, + ContactEnrollmentState, + decideContactRequest, + initialContactEnrollment, + reduceContactEnrollment, + reviewContactRequest, +} from 'src/services/wallets/recoverable/contactRecoveryFlow'; +import { + HARDWARE_CHOICES, + canPreviewInheritanceForHardware, + initialPreviewDraft, + PreviewAction, + PreviewDraft, + reducePreviewDraft, +} from './previewFlow'; +import { + initialSimulatedSetupState, + reduceSimulatedSetup, + SimulatedSetupState, +} from './simulatedSetup'; + +type Palette = { + background: string; + card: string; + text: string; + muted: string; + border: string; + accent: string; + warning: string; +}; + +type PreviewSurface = + | 'wallets' + | 'chooser' + | 'simple' + | 'hot' + | 'cold' + | 'advanced' + | 'import' + | 'seedless' + | 'mobile-key-diagnostic' + | '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, +}; +const SIMULATED_KEY_STEP_MS = 800; + +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 [surface, setSurface] = useState('wallets'); + const [choiceOrigin, setChoiceOrigin] = useState<'wallets' | 'chooser'>('wallets'); + const [draft, setDraft] = useState(initialPreviewDraft); + const [automaticSetup, setAutomaticSetup] = useState( + 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'>( + '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 resetWalkthrough = () => { + act({ type: 'RESET' }); + setAutomaticSetup(initialSimulatedSetupState); + setShowHowItWorks(false); + }; + const exitFlow = () => setSurface(choiceOrigin); + const openChoice = (choice: PreviewSurface) => { + setChoiceOrigin(surface === 'chooser' ? 'chooser' : 'wallets'); + setSurface(choice); + }; + const openRecoveryOptions = () => { + setContactEnrollment( + reduceContactEnrollment(initialContactEnrollment, { + type: 'START', + assurance: 'cloud-and-contact', + walletPolicyHash: SAMPLE_POLICY_HASH, + }) + ); + setContactSample('overview'); + setInvitationDecision('pending'); + 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'); + }; + 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 (surface === 'cloud' || surface === 'contact') setSurface('recovery'); + else if (surface === 'recovery') setSurface('seedless'); + 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); + else if (surface === 'seedless' && draft.stage === 'complete') { + resetWalkthrough(); + exitFlow(); + } else if (surface === 'seedless' && draft.stage === 'automatic') exitFlow(); + else if (surface === 'seedless') act({ type: 'BACK' }); + }; + + useEffect(() => { + const subscription = BackHandler.addEventListener('hardwareBackPress', () => { + if (surface === 'wallets') return false; + back(); + return true; + }); + return () => subscription.remove(); + }, [surface, draft.stage, choiceOrigin]); + + useEffect(() => { + scrollRef.current?.scrollTo({ y: 0, animated: false }); + }, [surface, draft.stage]); + + useEffect(() => { + 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( + () => setAutomaticSetup((current) => reduceSimulatedSetup(current, 'COMPLETE_STEP')), + SIMULATED_KEY_STEP_MS + ); + return () => clearTimeout(timer); + }, [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 = + automaticSetup !== initialSimulatedSetupState || + draft.stage !== 'automatic' || + draft.hardware !== null || + draft.inheritanceEnabled; + const walletChooser = (fromWallets: boolean) => ( + openChoice('simple')} + onSeedlessWallet={() => openChoice('seedless')} + onAdvancedWallet={() => openChoice('advanced')} + onImportWallet={() => openChoice('import')} + showSeedless + previewNotice={ + fromWallets + ? undefined + : 'TESTNET PREVIEW · Simulated choices. No wallet, address, or backup is created.' + } + seedlessResumeHint={ + hasDraft ? 'Your Assisted Multisig walkthrough will resume where you left off.' : undefined + } + /> + ); + + return ( + + + + {surface !== 'chooser' && ( + + {surface === 'wallets' + ? 'TESTNET DEMO · No spendable wallet or backup.' + : surface === 'seedless' + ? '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.'} + + )} + + {surface === 'wallets' && ( + + + 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. The second read cannot create a replacement. + 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" + /> + + )} + + {surface === 'chooser' && walletChooser(false)} + + {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 · Single-Key Wallet creation is not available in this preview. No + wallet, address, or backup exists. + + + + )} + + {surface === 'advanced' && ( + + + Custom setup + + + Custom Wallet is for choosing your keys and spending rules, including Miniscript + options such as Inheritance Key, Emergency Key, and Wallet Timelock. + + + PREVIEW ONLY · Custom Wallet creation is not connected in this isolated app. No + policy, key, or wallet is created. + + + )} + + {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' && ( + + + Setting up your keys + + + Mobile and Server first. Choose hardware next. + + + + + {automaticSetup === 'adding-mobile' ? ( + + ) : ( + + {automaticSetup === 'mobile-failed' ? '!' : '✓'} + + )} + + + Mobile Key + + + {automaticSetup === 'adding-mobile' + ? 'Adding… · SIMULATED' + : automaticSetup === 'mobile-failed' + ? 'Failed · SIMULATED' + : 'Added · SIMULATED'} + + + + + + + {automaticSetup === 'adding-server' ? ( + + ) : ( + + {automaticSetup === 'server-failed' + ? '!' + : automaticSetup === 'ready' + ? '✓' + : '○'} + + )} + + + Server Key + + + {automaticSetup === 'adding-server' + ? 'Adding… · SIMULATED' + : automaticSetup === 'server-failed' + ? 'Failed · SIMULATED' + : automaticSetup === 'ready' + ? 'Added · SIMULATED' + : 'Waiting · SIMULATED'} + + + + + + + + ○ + + + + Hardware Key + + + {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. + + )} + 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)} + 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. + + + )} + + + )} + + {surface === 'seedless' && draft.stage === 'hardware' && ( + + + Choose Hardware + + + Choose a device for the last key. Connection and policy support are not verified here. + + {HARDWARE_CHOICES.map((choice) => ( + act({ type: 'SELECT_HARDWARE', hardware: choice.id })} + > + + + {choice.id} + + {choice.transport} + {choice.verification} + + + ))} + act({ type: 'NEXT' })} + palette={palette} + /> + + + )} + + {surface === 'seedless' && 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" + /> + + + )} + + {surface === 'seedless' && draft.stage === 'inheritance' && ( + + + Inheritance Key + + {canProposeInheritance ? ( + <> + + 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. + + + 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" + /> + + + )} + + {surface === 'seedless' && 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. + + + Your signing device may have its own backup steps. + + + + + Inheritance · {draft.inheritanceEnabled ? 'selected' : 'not added'} + + + {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. 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.`} + + + + 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} + /> + + + )} + + {surface === 'seedless' && 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. + + + + + + )} + + {surface === 'recovery' && ( + + + Recovery Options + + + Explore proposed ways to restore this wallet's Mobile Key on another phone. These + options 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.'} + + )} + + + + )} + + )} + + + ); +} + +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' }, + 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: { + 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 0000000000..fb6bebf40b --- /dev/null +++ b/src/preview/recoverable-wallet/previewFlow.ts @@ -0,0 +1,111 @@ +export const HARDWARE_CHOICES = [ + { + id: 'TAPSIGNER', + transport: 'NFC', + verification: 'Inheritance Key unavailable; the card cannot verify the full delayed policy.', + }, + { + id: 'Satochip', + transport: 'NFC', + verification: 'Inheritance Key unavailable; the card cannot verify the full delayed policy.', + }, + { + id: 'Jade', + transport: 'QR or Keeper Desktop USB', + verification: 'Inheritance Key unavailable; full policy verification is not yet supported.', + }, + { + id: 'Coldcard', + transport: 'QR, file, NFC, or Keeper Desktop USB', + 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' + | '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: 'CHANGE_HARDWARE' } + | { 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, inheritanceEnabled: false } + : 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' && + (!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 && + (!draft.inheritanceEnabled || canPreviewInheritanceForHardware(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 0000000000..0573338b27 --- /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/src/preview/recoverable-wallet/simulatedSetup.ts b/src/preview/recoverable-wallet/simulatedSetup.ts new file mode 100644 index 0000000000..9a3364e7e5 --- /dev/null +++ b/src/preview/recoverable-wallet/simulatedSetup.ts @@ -0,0 +1,39 @@ +/** UI-only walkthrough state. None of these transitions create or verify a key. */ +export type SimulatedSetupState = + | 'adding-mobile' + | 'mobile-failed' + | 'adding-server' + | 'server-failed' + | 'ready'; + +export type SimulatedSetupAction = + | 'COMPLETE_STEP' + | 'SIMULATE_FAILURE' + | 'SHOW_SERVER_FAILURE' + | 'RETRY'; + +export const initialSimulatedSetupState: SimulatedSetupState = 'adding-mobile'; + +export function reduceSimulatedSetup( + state: SimulatedSetupState, + action: SimulatedSetupAction +): SimulatedSetupState { + switch (action) { + case 'COMPLETE_STEP': + if (state === 'adding-mobile') return 'adding-server'; + if (state === 'adding-server') return 'ready'; + return state; + case 'SIMULATE_FAILURE': + if (state === 'adding-mobile') return 'mobile-failed'; + if (state === 'adding-server') return 'server-failed'; + return state; + case 'SHOW_SERVER_FAILURE': + return state === 'ready' ? 'server-failed' : state; + case 'RETRY': + if (state === 'mobile-failed') return 'adding-mobile'; + if (state === 'server-failed') return 'adding-server'; + return state; + default: + return state; + } +} diff --git a/src/screens/AddWalletScreen/WalletChoiceScreen.tsx b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx new file mode 100644 index 0000000000..251cb9e535 --- /dev/null +++ b/src/screens/AddWalletScreen/WalletChoiceScreen.tsx @@ -0,0 +1,138 @@ +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'; +type WalletChoiceRoute = { params?: { initialStage?: 'simple' | 'seedless' } }; + +export default function WalletChoiceScreen({ route }: { route?: WalletChoiceRoute }) { + 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 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') { + if (initialStage) navigation.goBack(); + else setStage('chooser'); + } else navigation.goBack(); + }; + + const title = + stage === 'chooser' + ? 'Choose a Wallet' + : stage === 'simple' + ? 'Single-Key Wallet' + : stage === 'hot' + ? 'Hot Wallet' + : stage === 'cold' + ? 'Cold Wallet' + : 'Assisted Multisig'; + + return ( + + + + {stage === 'chooser' && ( + setStage('simple')} + onSeedlessWallet={() => setStage('seedless')} + onAdvancedWallet={() => navigation.navigate('AddNewWallet')} + onImportWallet={() => navigation.navigate('VaultConfigurationCreation')} + showSeedless + previewNotice="TESTNET PREVIEW · Assisted Multisig setup is simulated; no wallet is created." + /> + )} + {stage === 'simple' && ( + + + Choose where you want to hold the key. + + 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 Assisted Multisig 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/HomeScreen.tsx b/src/screens/Home/HomeScreen.tsx index d6846a9e42..3219c344b3 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 f277a0b79a..8db24fc324 100644 --- a/src/screens/Home/components/Wallet/HomeWallet.tsx +++ b/src/screens/Home/components/Wallet/HomeWallet.tsx @@ -1,7 +1,9 @@ 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 DashedCta from 'src/components/DashedCta'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import WalletCreationChooser from 'src/components/WalletCreationChooser'; import WalletCard from './WalletCard'; import Colors from 'src/theme/Colors'; import useWallets from 'src/hooks/useWallets'; @@ -10,8 +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, VisibilityType, WalletType } from 'src/services/wallets/enums'; -import { useNavigation, useFocusEffect, CommonActions } from '@react-navigation/native'; +import { EntityKind, NetworkType, VisibilityType } from 'src/services/wallets/enums'; +import { isEmptyWalletOnboardingEnabled } from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; +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'; @@ -23,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'; @@ -105,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); @@ -139,13 +139,18 @@ 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 = (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); @@ -280,13 +285,38 @@ const HomeWallet = () => { return ( - } - onPress={() => setPickWalletType(true)} - /> + {!showWalletEmptyState && ( + } + onPress={() => (usePreviewWalletChooser ? openWalletChoice() : setPickWalletType(true))} + /> + )} + + No wallets yet + + openWalletChoice('simple')} + onSeedlessWallet={() => openWalletChoice('seedless')} + onAdvancedWallet={() => + navigation.dispatch(CommonActions.navigate({ name: 'AddNewWallet' })) + } + onImportWallet={() => + navigation.dispatch( + CommonActions.navigate({ name: 'VaultConfigurationCreation' }) + ) + } + showSeedless + previewNotice="TESTNET PREVIEW · Seedless setup is simulated; no Seedless Wallet is created." + /> + + ) : null + } refreshControl={} keyExtractor={(item, index) => `${item.id || index}`} showsVerticalScrollIndicator={false} @@ -441,6 +471,13 @@ const styles = StyleSheet.create({ walletContainer: { gap: 15, }, + emptyWalletContainer: { + paddingTop: hp(10), + paddingHorizontal: wp(18), + paddingBottom: hp(28), + gap: hp(8), + }, + 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 new file mode 100644 index 0000000000..5ae5a6cf2a --- /dev/null +++ b/src/services/wallets/operations/recoverable/emptyWalletOnboarding.ts @@ -0,0 +1,42 @@ +import { getPreviewRuntime } from 'src/preview/recoverable-wallet/previewRuntime'; +import { NetworkType } from 'src/services/wallets/enums'; + +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; + +/** 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 new file mode 100644 index 0000000000..57f94945e3 --- /dev/null +++ b/src/services/wallets/operations/recoverable/mobileKey.ts @@ -0,0 +1,79 @@ +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; +} + +/** + * 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 +): 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 0000000000..e20ac289ea --- /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 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; +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 0000000000..c09029fee5 --- /dev/null +++ b/src/services/wallets/operations/recoverable/mobileKeyOrdinal.ts @@ -0,0 +1,139 @@ +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 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. */ + 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 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. + */ +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 0000000000..155be5c520 --- /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/deviceMobileKey.ts b/src/services/wallets/recoverable/deviceMobileKey.ts new file mode 100644 index 0000000000..b3c44c67da --- /dev/null +++ b/src/services/wallets/recoverable/deviceMobileKey.ts @@ -0,0 +1,159 @@ +import BIP32Factory from 'bip32'; +import * as bitcoin from 'bitcoinjs-lib'; +import { Buffer } from 'buffer'; +import NativeConfig from 'react-native-config'; +import DeviceInfo from 'react-native-device-info'; +import { getPreviewRuntime } from 'src/preview/recoverable-wallet/previewRuntime'; +import { SignerType } from '../enums'; +import ecc from '../operations/taproot-utils/noble_ecc'; +import { RECOVERABLE_MOBILE_KEY_SIGNER_PATH } from '../operations/recoverable/mobileKeyConstants'; +import type { RecoverableMobileSigner } from './policyDraft'; + +const bip32 = BIP32Factory(ecc); +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 { + constructor(public readonly code: string, message: string) { + super(message); + this.name = 'DeviceMobileKeyError'; + } +} + +/** 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'); + } + 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, + sourceId: `device-generated:${xpub}`, + }, + }; +} + +function decodeNativeSeed(base64: string): Buffer { + // 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'); + if (seed.length !== 32 || seed.toString('base64') !== base64) { + seed.fill(0); + throw new DeviceMobileKeyError('INVALID_NATIVE_SEED', 'Native Mobile Key is invalid'); + } + return seed; +} + +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'); + } + const module = NativeModules.KeeperPreviewMobileKey as DeviceMobileKeyAdapters | undefined; + if (!module || typeof module.getOrCreateSeedBase64 !== 'function') { + throw new DeviceMobileKeyError( + 'NATIVE_KEY_UNAVAILABLE', + 'Native Mobile Key store is unavailable' + ); + } + return module; +} + +const inFlight = new Map>(); + +/** + * Preview-only, testnet-only key preparation. This is intentionally not wired + * to wallet creation, signing, backup, or the simulated "Added" status. + */ +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 { + 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 requires the testnet preview app') + ); + } + + 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[operation]!(); + } 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(requestId, task); + const clear = () => { + 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 new file mode 100644 index 0000000000..1682b9cd87 --- /dev/null +++ b/src/services/wallets/recoverable/hardwarePublicImport.ts @@ -0,0 +1,224 @@ +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) || + ![Object.prototype, null].includes(Object.getPrototypeOf(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; + 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); + 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: descriptor.value, 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'); + } + 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); + 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 new file mode 100644 index 0000000000..9b4d62b905 --- /dev/null +++ b/src/services/wallets/recoverable/policyDraft.ts @@ -0,0 +1,569 @@ +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'; +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 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: RecoverableMobileOrigin; +} + +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`); + } + 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 { + 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`); + } + } +} + +function normalizePublicSigner( + signer: T, + role: T['role'] +): T { + 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 || '')) { + 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.signerType !== SignerType.MOBILE_KEY || + normalized.derivationPath !== MOBILE_KEY_SIGNER_PATH || + !normalized.origin || + 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') { + 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', + signerType: SignerType.MOBILE_KEY, + masterFingerprint: normalized.masterFingerprint, + xpub: normalized.xpub, + derivationPath: normalized.derivationPath, + origin, + }; +} + +/** 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( + 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' || + !Object.values(SignerType).includes(signer.signerType) || + signer.signerType === SignerType.UNKOWN_SIGNER || + 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(); + const accountPubkeys = new Set(); + for (const signer of signers) { + // 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); + } +} + +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 = validateRecoverableHardwareSigner(input.hardware); + const server = validateServer(input.server); + 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. + 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/services/wallets/recoverable/previewMobileKeyBackup.ts b/src/services/wallets/recoverable/previewMobileKeyBackup.ts new file mode 100644 index 0000000000..f83f59e4a8 --- /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 new file mode 100644 index 0000000000..2a5c706191 --- /dev/null +++ b/src/services/wallets/recoverable/previewMobileKeyReadback.ts @@ -0,0 +1,115 @@ +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 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 + * 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 snapshotExpectedPreviewSigner(signer: RecoverableMobileSigner): { + masterFingerprint: string; + xpub: string; + derivationPath: string; + sourceId: string; +} { + 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.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' + ); + } + // 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 ( + first.masterFingerprint !== second.masterFingerprint || + first.xpub !== second.xpub || + first.derivationPath !== second.derivationPath || + first.sourceId !== second.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, + }; +} diff --git a/src/services/wallets/recoverable/testnetScriptVector.ts b/src/services/wallets/recoverable/testnetScriptVector.ts new file mode 100644 index 0000000000..c6bac6e50f --- /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, + }; +} diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts index 063d9dc263..bdc95dfb22 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 08d87d3502..18810164e3 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 99eaa08f39..ffe1131d12 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/native/preview-mobile-key/KeeperPreviewMobileKeyStoreTest.kt b/tests/native/preview-mobile-key/KeeperPreviewMobileKeyStoreTest.kt new file mode 100644 index 0000000000..2b321b8417 --- /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 0000000000..4124cd3ed4 --- /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 0000000000..072dfb679d --- /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/homeScreenEducationGate.test.tsx b/tests/preview/homeScreenEducationGate.test.tsx new file mode 100644 index 0000000000..905757d623 --- /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 0000000000..cb323ba824 --- /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/previewAppBoundary.test.tsx b/tests/preview/previewAppBoundary.test.tsx new file mode 100644 index 0000000000..3958cae78f --- /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 0000000000..30562be5ba --- /dev/null +++ b/tests/preview/recoverableWalletPreview.test.ts @@ -0,0 +1,146 @@ +import { + getPreviewRuntime, + PREVIEW_BUNDLE_IDS, +} from '../../src/preview/recoverable-wallet/previewRuntime'; +import { + HARDWARE_CHOICES, + 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)( + '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('Coldcard inheritance remains an unverified proposal before one final review', () => { + 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: 'NEXT' }); + expect(draft).toMatchObject({ + stage: 'review', + hardware: 'Coldcard', + 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.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' }); + 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 0000000000..553f744431 --- /dev/null +++ b/tests/preview/recoverableWalletScreen.test.tsx @@ -0,0 +1,455 @@ +import React from 'react'; +import { Dimensions, PixelRatio, StyleSheet } from 'react-native'; +import { NativeBaseProvider } from '@gluestack-ui/themed-native-base'; +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'); + 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}; +}); + +function finishSimulatedAutomaticSetup() { + act(() => jest.advanceTimersByTime(800)); + act(() => jest.advanceTimersByTime(800)); +} + +function enterRecoveryOptions(screen) { + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + 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')); + 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(() => { + (checkPreviewMobileKeyReadback as jest.Mock).mockReset(); + jest.useFakeTimers(); + jest + .spyOn(Dimensions, 'get') + .mockReturnValue({ width: 320, height: 640, scale: 2, fontScale: 1.6 }); + jest.spyOn(PixelRatio, 'getFontScale').mockReturnValue(1.6); + }); + + afterEach(() => { + jest.useRealTimers(); + 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'); + expect(screen.queryByTestId('primary-Add Wallet')).toBeNull(); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(screen.getByTestId('preview-simulation-banner')).toHaveTextContent('TESTNET DEMO'); + 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('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 with Server Key alone/); + expect(serverWarning.props.allowFontScaling).toBe(true); + expect(StyleSheet.flatten(serverWarning.props.style).lineHeight).toBeGreaterThan(23); + const primaryLabel = screen.getByText('Choose Hardware'); + expect(primaryLabel.props.allowFontScaling).toBe(true); + expect(primaryLabel.props.numberOfLines).toBeUndefined(); + expect(screen.getByTestId('preview-how-it-works-details')).toHaveTextContent( + 'No key material has been generated' + ); + }); + + 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')); + 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')); + 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')); + 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')); + 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'); + 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' + ); + 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('preview-wallets-empty')).toHaveTextContent('Assisted Multisig'); + fireEvent.press(screen.getByTestId('wallet-choice-seedless')); + expect(screen.getByTestId('preview-mobile-key-status')).toHaveTextContent( + 'Adding… · SIMULATED' + ); + }); + + 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'); + expect(chooser).toHaveTextContent('Single-Key Wallet'); + expect(chooser).toHaveTextContent('Assisted Multisig'); + 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).not.toHaveTextContent('FEATURED'); + expect(chooser).not.toHaveTextContent('SINGLE KEY'); + expect(chooser).not.toHaveTextContent('CUSTOM MULTISIG'); + 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); + + 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( + 'Custom 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')); + expect(screen.getByTestId('preview-wallets-empty')).toHaveTextContent('No wallets yet'); + }); + + test('the shared chooser hides Assisted Multisig 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 0000000000..d471040f46 --- /dev/null +++ b/tests/preview/walletChoiceScreen.test.tsx @@ -0,0 +1,132 @@ +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(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', () => { + const screen = render(); + 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( + '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 0000000000..aed54b8e02 --- /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 0000000000..5857b77980 --- /dev/null +++ b/tests/services/emptyWalletOnboarding.test.ts @@ -0,0 +1,85 @@ +import { + isEmptyWalletOnboardingEnabled, + shouldAutomaticallyCreateMobileWallet, + shouldDeferRecoveryKeyEducation, + shouldRestoreFallbackMobileWallet, +} from 'src/services/wallets/operations/recoverable/emptyWalletOnboarding'; +import { NetworkType } from 'src/services/wallets/enums'; + +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); + }); + + 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/emptyWalletSetupSaga.test.ts b/tests/services/emptyWalletSetupSaga.test.ts new file mode 100644 index 0000000000..48f27188eb --- /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 0000000000..3b655cc06c --- /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/deviceMobileKey.test.ts b/tests/services/recoverable/deviceMobileKey.test.ts new file mode 100644 index 0000000000..3e1ec66a85 --- /dev/null +++ b/tests/services/recoverable/deviceMobileKey.test.ts @@ -0,0 +1,214 @@ +import { + deriveDeviceMobileKeyPublic, + getOrCreatePreviewDeviceMobileKey, + readExistingPreviewDeviceMobileKey, + 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 seed = Buffer.from('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', 'hex'); +const androidPreviewId = 'io.hexawallet.keeper.recoverablepreview'; +const iosPreviewId = 'io.hexawallet.hexakeeper.recoverablepreview'; + +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).mockReset().mockReturnValue(androidPreviewId); + }); + + it('derives a stable testnet BIP48 public signer without returning the 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' + ); + expect(JSON.stringify(signer)).not.toContain(seed.toString('hex')); + }); + + 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([ + { 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(native.getOrCreateSeedBase64).not.toHaveBeenCalled(); + }); + + it('fails closed when installed package identity cannot be read', async () => { + (DeviceInfo.getBundleId as jest.Mock).mockImplementation(() => { + throw new Error('native identity unavailable'); + }); + const native = adapter(); + await expect(getOrCreatePreviewDeviceMobileKey(native)).rejects.toMatchObject({ + code: 'PREVIEW_ONLY', + }); + expect(native.getOrCreateSeedBase64).not.toHaveBeenCalled(); + }); + + it('fails closed without the preview native key module', async () => { + await expect(getOrCreatePreviewDeviceMobileKey()).rejects.toMatchObject({ + code: 'NATIVE_KEY_UNAVAILABLE', + }); + }); + + 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.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({ + code: 'INVALID_NATIVE_SEED', + }); + } + ); + + 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('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 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(native.getOrCreateSeedBase64).toHaveBeenCalledTimes(1); + 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 new file mode 100644 index 0000000000..1077a0dd3f --- /dev/null +++ b/tests/services/recoverable/hardwarePublicImport.test.ts @@ -0,0 +1,380 @@ +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' + ); + }); + + 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 new file mode 100644 index 0000000000..df5678b4d8 --- /dev/null +++ b/tests/services/recoverable/policyDraft.test.ts @@ -0,0 +1,389 @@ +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 { + 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: 'device-generated', + version: 1, + sourceId: 'preview-device-mobile-key-1', + }, + }; + 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 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: { + 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(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; + 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); + 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( + (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 malformed Mobile Key origin 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 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'); + }); + + 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.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; + 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' + ); + }); + + 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 0000000000..d8be94d9cf --- /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 new file mode 100644 index 0000000000..ab0100e92b --- /dev/null +++ b/tests/services/recoverable/previewMobileKeyReadback.test.ts @@ -0,0 +1,160 @@ +import { Buffer } from 'buffer'; +import { + deriveDeviceMobileKeyPublic, + 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, + 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, 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, + 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, 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, 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, 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, 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 new file mode 100644 index 0000000000..fef26d96d4 --- /dev/null +++ b/tests/services/recoverable/testnetScriptVector.test.ts @@ -0,0 +1,336 @@ +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'; +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' }, + }, + }; +} + +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 + // 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('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 = { + 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. + 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 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); + }); +}); diff --git a/tests/services/recoverableMobileKey.test.ts b/tests/services/recoverableMobileKey.test.ts new file mode 100644 index 0000000000..629dbcc6a5 --- /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 0000000000..10465312b7 --- /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'); + }); +});