HISTORICAL IMPLEMENTATION NOTES — not the normative recovery contract.
Current contract: docs/RECOVERY.txt; current project entry: resatoshi/README.md.

# ReSatoshi Wallet — Android preview

This is an independent Android fork of BlueWallet, not an official BlueWallet
product. Upstream source: `https://github.com/BlueWallet/BlueWallet`, commit
`629fcca52430a6ac5027c56b9f5f00f58b1b6359`. Branch:
`feature/resatoshi-wallet`. Original source and MIT notices are retained in Git.
The original package manifest is recorded in `upstream-package.json`.

The Android build uses a separate entry screen and native source set so inherited
Bitcoin, Lightning, Ark, fiat-price widgets, analytics and third-party purchase
flows cannot be reached from the preview. It reuses BlueWallet's ECC adapter,
React Native/Android foundation and wallet dependencies. Upstream Bitcoin wallet
classes remain in the source for reference; they are not Resatoshi-compatible
and are not imported by the app entry point. The iOS project is not adapted.

## Current functionality

- Generate a 24-word BIP39 seed using Android SecureRandom through an async native
  method, or restore a valid English BIP39 seed. Creation failures show C01–C03
  instead of escaping the button handler; render failures show C04 via an error
  boundary. No weak-RNG fallback is permitted for wallet creation.
- Optionally use a BIP39 passphrase on creation/restoration, with confirmation
  entry and separate-backup acknowledgement. NFKD normalization is applied;
  leading/trailing spaces and case are never trimmed or changed.
- Store the mnemonic and optional passphrase with Android Keychain and device authentication; optionally encrypt the payload with a separate wallet password first. Device screen
  lock is required; app backup is disabled and screenshots are blocked.
- Lock the session when the app leaves the foreground, except for a bounded,
  explicitly requested system authentication flow covered by an opaque app screen.
- Generate Resatoshi native SegWit receiving addresses, QR codes and sharing.
- Discover receiving/change addresses through a manually configured Electrum TLS
  server. No default Bitcoin server, peer discovery or non-TLS fallback.
- Check the server's actual genesis header against Resatoshi mainnet.
- Calculate spendable balance from validated raw-transaction outputs; exclude
  immature coinbase, unconfirmed and expired outputs.
- Scan a plain Resatoshi address QR using the rear camera; camera permission is
  requested only when opening the scanner. QR processing is on device and does
  not need Google Play Services. Cancel/denial leaves manual address entry available.
  Payment URIs are not supported. Scanning clears previous amount/prepared payment
  and never broadcasts automatically.
- Review amount, destination and fee, then authenticate and broadcast a signed
  native SegWit transaction. Do not automatically retry an ambiguous broadcast.
- Refresh transaction IDs/confirmation counts from the server.
- Show original MIT and installed dependency notices inside the app.

This is a server-trusting light wallet, not an SPV/full-chain validator. A genesis
check prevents accidental Bitcoin connections but does not establish that an
untrusted server is reporting the honest chain. It does not verify header PoW,
ASERT or Merkle inclusion. The server sees queried script hashes and the client's
IP. No seed, xprv or private key is sent to it. An attacker with sustained majority
hashrate can reverse confirmations; the UI does not promise transaction finality.

## Recovery convention — must accompany the seed

```
Network: Resatoshi mainnet
Mnemonic: English BIP39
BIP39 passphrase: the exact selected passphrase, or empty if not enabled
Account: m/84'/19333'/0'
Receive: account/0/index
Change: account/1/index
Address prefix: rsat1
```

`19333` is a fork-local derivation convention, NOT a registered SLIP-0044 coin
type. Keeping it different from Bitcoin avoids silently reusing Bitcoin account
keys. Do not change this path after wallets have been created without an explicit
migration/import design. Receiving-address recovery stops after 20 unused addresses, with a 2,000-address
cap. Every change address from 0 through 1999 is checked regardless of gaps,
matching the complete range accepted by the QR signer. Hitting the receiving cap
without completing the gap is an error. After change index 1999 is used, new
change allocation fails explicitly rather than selecting an unscanned address. The app does not import Bitcoin Core wallet files.

Passphrase wallets need the mnemonic, the exact passphrase and this account path
to recover. Every passphrase (including a typo) produces a valid different wallet;
the app cannot determine correctness from the mnemonic alone. Keep a first receive
address with the backup for comparison. The passphrase is distinct from Android
device authentication. Storing it with the mnemonic is a usability choice: it is
encrypted by Android Keychain (and the optional wallet password), but this does not
protect secrets from compromise of an already unlocked app. It is never stored in AsyncStorage or sent to Electrum.

Records written by 0.1.0/0.1.1 are read as an empty-passphrase wallet, without
rewriting the existing record or changing its addresses/keychain service. New
records use a validated version-2 payload (older app versions cannot open new
version-2 records); an invalid/missing passphrase field
fails closed instead of silently opening the empty-passphrase wallet.

The lock screen's **Open with a different passphrase** opens another wallet derived from
the stored mnemonic. It shows the first address for confirmation and affects
only the unlocked session; it does not overwrite the stored default wallet or
move any funds. Entering an empty override opens the no-passphrase wallet.
Ordinary unlock continues to open the stored default wallet. Merely setting a
passphrase does not migrate coins from the original wallet to the new one.

## Required server

There is **no deployed or bundled Resatoshi Electrum backend in this change**.
An existing Bitcoin Electrum instance cannot be used by merely changing the app's
host setting. A backend must support Resatoshi's chain and expiry/reorg rules.

The app uses standard Electrum 1.4 methods:
`server.version`, `blockchain.block.header`, `blockchain.headers.subscribe`,
`blockchain.scripthash.get_history`, `blockchain.scripthash.listunspent`,
`blockchain.transaction.get` (raw hex) and `blockchain.transaction.broadcast`.
Use a publicly trusted TLS certificate matching the configured DNS name. The
postinstall patch enables Android TLS hostname validation, and Gradle refuses to
build if that patch is absent. Runtime wrong-host certificate behavior still
requires an Android device/emulator test.

Expiry is applied again in the client using the next block height: an output
created at h can be spent through h + 5,256,000 inclusive. Transaction history
must still be indexed correctly by the server, including spent/expired outputs
and reorgs. Unconfirmed funds are not included in the spendable balance. Fees
are entered manually in smallest units per vbyte; fiat pricing is not enabled.

## Build and validate

Requires Node >=22.13, JDK 17, Android SDK 36, build-tools 36.0.0, NDK
27.1.12297006 and CMake 3.22.1. Set `JAVA_HOME` and `ANDROID_HOME` to your local
installations. npm's postinstall applies the TLS patch and collects notices.

```sh
npm ci
npm run typecheck:resatoshi
npm run test:resatoshi
npm run bundle:android
cd android
./gradlew :app:assemblePreview --no-daemon
```

Preview APK: `android/app/build/outputs/apk/preview/app-preview.apk`. It bundles
the JS and runs without Metro. It uses an Android development signing key,
is not debuggable, and is for controlled testing only. Do not publish
it as a production release. The release build has no production signing key.
Application ID is `org.resatoshi.wallet`, version `0.1.4-preview`, ARM64 only.

Run an isolated actual Core acceptance check (never uses an existing node):

```sh
RESATOSHI_CORE_BIN=/path/to/resatoshi/bin node --import tsx scripts/resatoshi-core-check.ts
```

## Before general release

Provision and test a Resatoshi-aware backend; test real Android creation,
authentication, lock/resume, backup restoration and full receive/send flow;
exercise server disconnects, expired outputs and chain reorganizations end to
end. Verify live camera scanning on Android; add payment URI handling if needed. Select a production
signing key and review dependency licenses, privacy disclosures and store policy.
The current automated tests do not establish real-device security or mainnet
operational readiness. Never use the public seed from the test fixtures for funds.

## Reported device exit on wallet creation

A user reported an older preview closing when creating a wallet, without device
logs or an exact version. The original creation button called the synchronous
getRandomValues bridge without a try/catch; an exception could terminate the
release app. Version 0.1.3 replaces this path with an async Android SecureRandom
method, validates its 32-byte response, handles failures and cancels updates after
backgrounding. This hardens a confirmed uncaught-exception path; it does not
establish the specific root cause of the reported device exit. A device retest
or crash log is still required. Error dialogs never include the recovery phrase.

## Manual physical-dice creation (0.1.4)

The advanced create screen accepts exactly 128 physical six-sided die results,
with a counter, undo, and physical-roll acknowledgement. Input buttons do not
simulate rolls. The app does not certify randomness or claim the roll count alone
proves entropy. Do not invent results or use repeating patterns.

The immutable conversion is:

```
entropy = SHA256(ASCII("resatoshi-dice-v1") || 0x00 || ASCII(128 digits 1..6))
mnemonic = BIP39_English_24_words(entropy)
```

No OS entropy is mixed into the dice seed. For fair independent dice, 128 rolls
supply about 330.9 bits before SHA256 compresses the result to 256 bits. Hashing
cannot create missing entropy. The raw rolls are not saved, logged or transmitted;
leaving the app clears input. Roll records are themselves wallet secrets.
`scripts/verify-dice.py` independently reproduces the conversion offline, using
hidden terminal input and the installed English wordlist. Never put real roll
sequences in command-line arguments or send them to a website.

## Optional wallet-password encryption and files (0.1.4)

A wallet password encrypts storage and backups and does not change wallet keys or
addresses. It is distinct from the BIP39 passphrase. Creation/restoration supports
an optional wallet password; an existing default wallet can enable/change it in
Settings > Wallet password · Encrypted backup. New passwords require a confirmation, at least
12 Unicode code points, a non-whitespace character and at most 1,024 UTF-8 bytes.
File passwords preserve exact UTF-8, spaces and case; no Unicode normalization is
applied to them. Long unique passwords are recommended. Password strength is not
certified by the minimum length.

The portable format uses `@noble/hashes` scrypt (N=32768, r=8, p=3, dkLen=32,
about 32 MiB workspace) and `@noble/ciphers` AES-256-GCM with a 32-byte salt and
12-byte nonce from Android SecureRandom. This salt/nonce generation does not
change a manually generated seed. Canonical authenticated metadata binds format,
version, network genesis, derivation account, fixed KDF, salt, cipher and nonce.
Ciphertext includes the 16-byte authentication tag. The algorithm/work factors
are fixed and checked before KDF; files are limited to 16 KiB to reject hostile
work-factor/memory requests. The parameters follow one of OWASP's scrypt
CPU/memory tradeoffs: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html

Version-3 Keychain records contain only this encrypted envelope under the original
service. No wallet password or derived encryption key is persisted. Typed key,
password-byte and plaintext buffers are wiped after use where possible; immutable
JS strings and in-flight KDF work cannot be guaranteed to disappear immediately.
Locking clears UI/session state, and completed operations check liveness before
saving. Android Keychain and device authentication remain required. Send approval
rechecks the stored credential, without caching a password or silently opening
an empty-passphrase wallet.

Before password migration/change, the app decrypts and checks the current record,
creates and verifies the new encrypted envelope, then replaces the Keychain
record. It does not create plaintext rollback files. Existing v1/v2 wallets remain
unchanged until the user opts in. New v3 records cannot be opened by older apps.
Changing a password does not change previous exported backups; export again.
Replacing a prior record is not a guarantee of erasing historical filesystem
snapshots or backups.

The Android Storage Access Framework saves `ReSatoshi-Wallet-Backup.rsatwallet`
without storage permissions or a temporary plaintext file. Only ciphertext goes
to the document picker. Opening the picker locks the session; return and unlock
again afterward. Restore is offered on the empty-wallet setup screen: select an
encrypted file, enter its file password, validate the authentication tag and secret,
then protect that envelope with the destination device's Keychain. An existing
wallet is not overwritten by file import. An alternate BIP39 session must reopen
the default wallet before password management/export, avoiding a misleading backup
of a different wallet. Neither export nor import sends data to our servers.

Offline attackers can guess passwords against copied encrypted files; UI attempt
limits would not prevent this. Losing a file password requires recovery from the
mnemonic plus any BIP39 passphrase and the documented account path. Encryption does
not protect an already unlocked wallet from a compromised phone or malicious app.
Physical-device Keychain migration, document picker I/O and mobile KDF performance
still require testing; do not treat the preview as independently audited.

## Numbered recovery and two-device QR signing (0.1.6)

Mnemonic restoration defaults to 24 individually numbered fields. The user may
choose 12/15/18/21/24 for existing English BIP39 backups. Pasting a phrase into
the first slot distributes words without shifting empty slots. Overflow and
missing slots are rejected, and spelling plus the final BIP39 checksum are checked.
Changing the word count clears the inputs to avoid silently truncating a backup.

The initial screen offers a public-only online watch wallet. The ordinary wallet
home screen offers **Sign transaction QR · Export public key**, with a return button to the
wallet home. There is no persistent online/offline mode, mode migration, airplane
requirement, network-state polling or automatic radio switching. Wallet unlock,
creation, recovery, receive addresses, QR review/signing and public-key export
work without internet. Balance lookup, transaction preparation from chain UTXOs
and broadcast require the configured online server and explicit user actions.
Opening the QR signer closes any wallet Electrum socket and clears the prior
snapshot/prepared payment; returning does not reconnect or refresh automatically.
The signing screen performs no network requests. Device reauthentication and
full transaction/signature checks remain required. App backgrounding locks the
session and discards the signing screen.

To use a real airgap, keep the signing phone physically disconnected from networks
from before key creation onward; disable Wi-Fi and Bluetooth too. The QR feature
does not isolate the phone or erase past online exposure. The APK has INTERNET
permission for ordinary wallet and public-only online watch functions.

Two-device flow:
1. On the disconnected signing phone, create/restore the wallet, unlock, open
   **Sign transaction QR · Export public key** from wallet home and export the watch QR.
2. On the online phone, choose the public-key watch wallet, scan every QR fragment,
   compare the first receive address on both phones, and save the public profile.
   Never enter the mnemonic/passphrase on the online phone.
3. Configure a Resatoshi-aware Electrum TLS server on the online phone, enter the
   destination/amount/fee, and prepare a transaction. No backend is supplied yet.
4. Scan the unsigned transaction QR on the offline phone. Read every output,
   destination, change amount and fee; authenticate explicitly to sign.
5. Scan the signed response on the online phone, review, and explicitly broadcast.
   Leaving the online screen/app invalidates the pending transaction. A changed
   chain tip requires preparing/signing again; no automatic retry is performed.

The public profile binds Resatoshi genesis, the fixed account path, account xpub,
master fingerprint and first address. Imported private extended keys are rejected.
It is stored in AsyncStorage (public data only), separate from Keychain secrets.
An xpub reveals account addresses/transactions and should not be publicly posted.
The profile's fingerprint/checksum does not authenticate its human owner; compare
addresses through the physical offline device.

Transactions use BIP174 PSBT v0 with SIGHASH_ALL, owned native SegWit inputs and
verified full previous transactions as well as witness UTXOs. The signer derives
keys independently, verifies previous txids/values/scripts, duplicate inputs,
paths/fingerprints, change ownership, and exact transaction structure. It permits
one payment plus optional change, at most 20 inputs and indices below 2,000.
Every output is shown, including change. Fixed bounds on size, paths and fees
limit hostile QR work. The offline phone cannot attest chain inclusion, expiry,
coinbase maturity or the honest tip without an independent chain source; online
scan checks retain the existing server-trusting limitations.

The signed response is bound to the exact request hash. Online validation checks
that all unsigned transaction bytes remain identical, and independently verifies
every witness signature before offering broadcast. Current transfers use an
app-specific `rsatqr1` chunk wrapper around the watch/PSBT/signed JSON envelopes,
not BC-UR or generic hardware-wallet compatibility. Each chunk carries a full
SHA256 set ID and sequence; reassembly rejects mixed/conflicting sets and checks
the complete digest. QR transfer is local camera/display only; no clipboard,
sharing, private key export or file transfer is required. Maximum payload is
180,000 bytes / 400 frames, 600 base64 characters per frame. Manual and automatic
frame stepping are available. A checksum detects corruption, not a malicious
coordinator; verify transaction details on the signer.

Verification includes malicious input/fee/change data, wrong wallet/network,
modified signatures/transactions, multi-input signing, fragmented QR assembly,
public-only scanning, and isolated Resatoshi Core mempool/mining/verifychain for
both passphrase modes. Physical two-phone camera, biometric timing, screen navigation and usability
remain untested. This is preview software, not an
audited hardware-wallet replacement, and does not mitigate chain majority attacks.

## 0.1.8: account-public-key QR connection only

Initial screen → **Watch-only wallet · Connect with public-key QR**. The watch screen is labelled
**Watch-only wallet for QR payments** and accepts only the account public-key QR exported by
the signing wallet. It covers receive and change addresses, can prepare a PSBT,
and can verify and broadcast the signed response. No one-line address import or
single-address balance lookup is provided. Removed the address-only profile,
scanner API and corresponding tests; account scan and signing behavior remain.
Normal send recipient address entry and receive-address QR sharing are retained.
The watch screen still shows account transaction IDs and confirmation counts.
There is no automatic Windows Core descriptor/QR interoperability in this build.
A Resatoshi-aware Electrum TLS server is required for live lookup/broadcast and
is still deferred. No secret credentials, key paths or backup formats changed.

## 0.1.9: fresh device approval and complete change recovery

Every secret read (unlock, send, QR sign, password/backup approval) and secret write
now starts an explicit native system authentication request. Android 11+ uses a
new strong-biometric-or-device-credential prompt for each call; API 24–29 uses a
new system PIN/pattern/password confirmation activity. Keystore's five-second
validity remains an additional storage protection and is not treated as a fresh
transaction approval. All get/set calls use the shared access-control options.
The old-Android Keychain prompt-builder compatibility patch is reapplied by
postinstall and checked by preBuild: STRONG|CREDENTIAL is unsupported there, so
its secondary prompt uses the compatible WEAK|CREDENTIAL combination. On those
versions our mandatory fresh native credential check precedes storage access;
weak biometrics alone cannot authorize the wallet operation.

Authorization rejects cancellation, false/non-boolean results, unavailable screen
lock, overlapping requests, timeout and a nonforeground app. Native requests have
a 60-second limit and generation-tagged callbacks; the JS flow has a 70-second
limit and ignores late results. A failed/late request cannot start a later storage
operation. Device-credential activities can temporarily background the app, so
only a currently owned, bounded authentication flow defers the normal background
cleanup. An opaque input-blocking cover hides the app until it ends. Other
backgrounding still locks/clears secrets; if auth ends while backgrounded, cleanup
runs then. Returning to foreground is required before reading/writing credentials
or completing signing. These Android activity/biometric behaviors still require
physical-device verification, especially PIN-only and older devices.

Change recovery no longer stops at an unused-address gap. A seed/xpub-only scan
covers all 2,000 accepted change indices, including deliberately skipped indices
25 and 1999. No server hint or locally remembered change index is required.
Reads are processed in windows of 16 addresses (32 history/UTXO requests), with
raw transaction fetches deduplicated, stable output ordering and the existing
full-prevout/maturity/expiry/chain-tip checks. Each batch settles before an error
is returned. This increases server traffic and lookup time; full scans can fail
and need repeating if the tip changes during lookup. The receive branch retains
its 20-unused gap rule. New offline and ordinary payments both reject a change
index outside the shared 0–1999 range; reaching the end gives an explicit error.
Account paths, existing addresses, vault formats and signing keys are unchanged.

New tests reproduce hidden change with two independent signed transactions, then
recover both balances without local hints. Authorization tests cover two fresh
requests despite cached credentials, cancellation, foreground failure, overlap,
store failure, timeout and late-result rejection. No physical authentication or
radio isolation claim is made from these unit tests.

## 0.1.10: live provisional incoming payments

Ordinary and public-only watch wallets display a separate **Unconfirmed incoming** panel.
A dedicated, public-only Electrum 1.4 TLS connection subscribes to
`blockchain.scripthash.subscribe` and header notifications. A script-hash push
schedules a targeted history lookup after a 25ms coalescing delay; it does not
wait for the full 2,000-address change recovery scan. Urgent script pushes take
precedence over periodic/header reconciliation. A 15-second reconciliation is a
fallback, not the primary notification mechanism. Server/node propagation and
network latency determine real end-to-end timing; the app cannot detect an
unbroadcast payment or promise instant receipt across an unavailable backend.

Monitoring starts only for saved/verified server settings. Editing a server stops
live monitoring until the new settings are checked/saved. A separate connection
lets QR preparation/signing and ordinary transaction scans retain their existing
validation. The monitor is unmounted when entering the QR signer and disconnected
on app background/lock; no Android background push service or OS notification is
implemented. The app must be open, foreground and connected. Disconnections mark
old results stale and retry with bounded backoff; generation checks discard old
connection callbacks. Cached public receive-index hints speed subscription setup
but do not replace the full account recovery scan.

Subscribe to previously allocated receiving addresses plus the receive lookahead,
prioritizing the currently displayed receive address. Account-public-key script
ownership is built locally over the supported 0..1999 range on both branches.
The raw incoming transaction's txid is checked; outputs to owned scripts are
summed once across addresses. Owned P2WPKH inputs are detected from their witness
public keys and their original transaction IDs/outputs are checked before the
owned input amounts are subtracted. Thus outgoing change/self-transfers are not
presented as external deposits. Only a positive net account inflow is listed.
This remains provisional server-reported mempool information, not chain/SPV or
full transaction validity verification, not sender identity authentication.

Pending deposits are never added to spendable coins or the confirmed balance.
Replacement/removal changes old entries to **No longer seen by server**, rather
than promising a final cancellation. Confirmation moves an entry to confirmed;
a reorg can move it back to pending. Confirmations/removals request a separate
balance refresh when no transaction workflow is active. The panel always warns
that mempool transactions can be replaced/double-spent and even confirmations
can reverse under a 51% attack/reorganization. Do not treat the display as final
payment settlement. Prior confirmed history remains available separately.

Deterministic TCP/protocol tests inject real notification envelopes and verify a
pending credit in <1 second after the push (after initial setup), no periodic
poll needed, multi-address deduplication, replacement, confirmation, reorg,
self-transfer exclusion, forged txid rejection and stop behavior. This is a local
fixture timing result, not a physical phone/live-network latency measurement.
The Resatoshi-aware Electrum backend is still not deployed; it must index mempool
history and emit subscription notifications for this feature to operate live.

### English default (0.1.11-preview)

All app-owned screens, warnings, errors, accessibility labels and native prompt
messages use English regardless of the device locale. Android-owned permission,
credential and file-picker controls may follow the device language. Recovery
words remain the BIP39 English word list. Wallet formats and derivation are unchanged.

### Publication preparation (0.1.12-preview)

Privacy and data handling is available on the initial/lock screen and in Settings,
using bundled privacy.json and generated ../PRIVACY.txt. No hosted operator or
retention policy is invented: those launch requirements remain explicitly pending.
The unused upstream Google configuration was removed from HEAD. The upstream
history and public test vectors are preserved. See ../SECURITY.md for fork-specific
reporting and ../RELEASE-READINESS.txt for production signing and legal review.
Dependency notices now include explicit Resatoshi modification attributions and
the limits of the npm inventory; native distribution review remains required.
