@bsv/expo-wallet-toolbox 0.5.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/CHANGELOG.md +2000 -0
  2. package/README.md +66 -1
  3. package/core/amountFormatHelpers.ts +258 -36
  4. package/core/backup/RemoteSyncReader.ts +133 -24
  5. package/core/backup/appData.ts +157 -0
  6. package/core/backup/client.ts +15 -1
  7. package/core/backup/codec.ts +149 -11
  8. package/core/backup/constants.ts +30 -1
  9. package/core/backup/cursor.ts +31 -2
  10. package/core/backup/push.ts +71 -5
  11. package/core/backup/restore.ts +104 -16
  12. package/core/backup/restoreOnImport.ts +94 -30
  13. package/core/backup/status.ts +13 -8
  14. package/core/config.tsx +12 -5
  15. package/core/constants.ts +14 -1
  16. package/core/contacts/contactActivity.ts +153 -0
  17. package/core/contacts/contactCache.ts +41 -0
  18. package/core/contacts/contactsStore.ts +183 -0
  19. package/core/context/ExchangeRateContext.tsx +34 -27
  20. package/core/context/LocalStorageProvider.tsx +43 -40
  21. package/core/context/UserContext.tsx +18 -7
  22. package/core/context/VaultContext.tsx +49 -2
  23. package/core/context/WalletConnectionContext.tsx +203 -11
  24. package/core/context/WalletContext.tsx +685 -171
  25. package/core/demo/demoAssets.ts +60 -0
  26. package/core/demo/demoLedger.ts +240 -0
  27. package/core/demo/demoMandalaRuntime.ts +96 -0
  28. package/core/demo/demoMode.ts +38 -0
  29. package/core/demo/demoWallet.ts +25 -0
  30. package/core/demo/index.ts +26 -0
  31. package/core/demo/useDemo.ts +59 -0
  32. package/core/headers/OfflineFirstChaintracks.ts +99 -17
  33. package/core/headers/headerStore.ts +33 -14
  34. package/core/headers/syncHeaders.ts +12 -1
  35. package/core/i18n/translations.tsx +2186 -98
  36. package/core/identity/contactLink.ts +36 -0
  37. package/core/identity/handleRegistry/client.ts +314 -0
  38. package/core/identity/handleRegistry/keyPinStore.ts +70 -0
  39. package/core/identity/handleRegistry/profileCert.ts +254 -0
  40. package/core/identity/handleRegistry/registration.ts +559 -0
  41. package/core/identity/handleRegistry/resolver.ts +315 -0
  42. package/core/identity/handleRegistry/rules.ts +104 -0
  43. package/core/index.ts +53 -5
  44. package/core/localpay/build.ts +225 -24
  45. package/core/localpay/pending.ts +110 -7
  46. package/core/localpay/pendingAbortAuthority.ts +95 -0
  47. package/core/localpay/pendingAborts.ts +266 -26
  48. package/core/localpay/session.ts +42 -17
  49. package/core/localpay/settlementAck.ts +10 -1
  50. package/core/localpay/transport/socket.ts +52 -3
  51. package/core/localpay/verify.ts +100 -10
  52. package/core/mandala/abortGuard.ts +96 -20
  53. package/core/mandala/createRuntime.ts +206 -33
  54. package/core/mandala/drain.ts +89 -11
  55. package/core/mandala/inboxPrehold.ts +186 -0
  56. package/core/mandala/permissionModule.ts +202 -20
  57. package/core/mandala/settlementStore.ts +24 -2
  58. package/core/mandala/types.ts +40 -5
  59. package/core/monitor/MonitorSupervisor.ts +121 -0
  60. package/core/monitor/TaskBackupPush.ts +15 -1
  61. package/core/monitor/TaskCreditInbox.ts +1 -1
  62. package/core/monitor/TaskDrainOutbox.ts +15 -1
  63. package/core/monitor/TaskSendOffline.ts +15 -1
  64. package/core/net/online.ts +49 -0
  65. package/core/net/publicDestination.ts +91 -0
  66. package/core/net/validateArcUrl.ts +22 -0
  67. package/core/numberFormat.ts +19 -0
  68. package/core/offline/cancelParked.ts +134 -13
  69. package/core/offline/payerHold.ts +100 -24
  70. package/core/offline/plan.ts +37 -8
  71. package/core/pay/beefRepair.ts +6 -2
  72. package/core/pay/damagedInbox.ts +24 -0
  73. package/core/pay/rails/address.ts +107 -12
  74. package/core/pay/rails/handle.ts +117 -22
  75. package/core/pay/rails/index.ts +45 -7
  76. package/core/pay/rails/nativeIntent.ts +61 -0
  77. package/core/pay/receiveHistory.ts +93 -0
  78. package/core/pay/recordProof.ts +21 -7
  79. package/core/pay/refreshProofGuard.ts +42 -1
  80. package/core/pay/watchlist.ts +5 -2
  81. package/core/peerpay/control.ts +17 -18
  82. package/core/peerpay/handleResendRequests.ts +58 -4
  83. package/core/peerpay/outbox.ts +3 -1
  84. package/core/recovery/backupMaterial.ts +61 -0
  85. package/core/recovery/createWallet.ts +95 -0
  86. package/core/recovery/recoverWallet.ts +120 -0
  87. package/core/recovery/restoreWallet.ts +170 -0
  88. package/core/recovery/secret.ts +92 -0
  89. package/core/recovery/shareCollector.ts +71 -0
  90. package/core/recovery/shareParsing.ts +87 -0
  91. package/core/recovery/shares.ts +116 -0
  92. package/core/recovery/useRecoveryDeps.ts +70 -0
  93. package/core/services/arcTokenStorage.ts +52 -0
  94. package/core/services/arcadeBroadcastProvider.ts +233 -52
  95. package/core/services/autoApprovePolicy.ts +105 -0
  96. package/core/services/callbackToken.ts +19 -0
  97. package/core/services/capWalletArgs.ts +14 -2
  98. package/core/services/connectionAuthority.ts +98 -0
  99. package/core/services/exchangeRate.ts +36 -13
  100. package/core/services/externalOrigin.ts +16 -2
  101. package/core/services/secrets/kek.ts +126 -29
  102. package/core/services/secrets/migration.ts +16 -4
  103. package/core/services/secrets/store.ts +42 -14
  104. package/core/services/vault/VaultKeyService.ts +228 -45
  105. package/core/services/vault/chainRecovery.ts +483 -0
  106. package/core/services/vault/driver.ts +9 -1
  107. package/core/services/vault/enrolledSerialRegistry.ts +150 -0
  108. package/core/services/vault/guard.ts +218 -32
  109. package/core/services/vault/hardwareLease.ts +19 -0
  110. package/core/services/vault/metaAuthority.ts +210 -0
  111. package/core/services/vault/pivReset.ts +64 -23
  112. package/core/services/vault/r1comb.ts +139 -3
  113. package/core/services/vault/session.ts +25 -4
  114. package/core/services/vault/transfers.ts +868 -172
  115. package/core/services/vault/types.ts +19 -4
  116. package/core/services/vault/vaultStore.ts +256 -29
  117. package/core/services/walletArgLimits.ts +45 -2
  118. package/core/services/walletConnectionValidation.ts +76 -6
  119. package/core/services/walletServiceConfig.ts +40 -27
  120. package/core/storage/StorageExpoSQLite.ts +88 -47
  121. package/core/storage/methods/findSql.ts +24 -2
  122. package/core/storage/methods/listActionsSql.ts +8 -5
  123. package/core/storage/methods/listOutputsSql.ts +2 -2
  124. package/core/storage/methods/offlineActions.ts +10 -1
  125. package/core/storage/methods/processOfflineActions.ts +117 -25
  126. package/core/storage/methods/reviewStatusSql.ts +7 -2
  127. package/core/storage/schema/createTables.ts +155 -2
  128. package/core/stores/ConnectionStore.ts +34 -0
  129. package/core/toolboxConfig.ts +104 -0
  130. package/core/toolboxTypes.ts +40 -0
  131. package/core/userAvatar.ts +79 -0
  132. package/core/walletDbRegistry.ts +63 -0
  133. package/core/walletMonitor.ts +25 -4
  134. package/core/walletRepair/releaseStuckReservations.ts +72 -0
  135. package/core/walletRepair/shouldMarkUnspendable.ts +20 -0
  136. package/core/walletRepair/spenderConsumesOutpoint.ts +29 -0
  137. package/package.json +7 -7
  138. package/ui/activityFilter.ts +115 -0
  139. package/ui/backupShares.ts +26 -169
  140. package/ui/components/pay/AddressReceive.tsx +13 -6
  141. package/ui/components/pay/AssetPicker.tsx +30 -9
  142. package/ui/components/pay/MessageBoxConfig.tsx +16 -0
  143. package/ui/components/pay/NearbyFlow.tsx +480 -243
  144. package/ui/components/pay/PaymentSuccessOverlay.tsx +85 -10
  145. package/ui/components/pay/RecipientField.tsx +84 -70
  146. package/ui/components/pay/StepBar.tsx +32 -0
  147. package/ui/components/pay/UniversalSend.tsx +827 -205
  148. package/ui/components/ui/AlertCard.tsx +38 -5
  149. package/ui/components/ui/PencilEditField.tsx +109 -0
  150. package/ui/components/ui/PermissionSheet.tsx +197 -66
  151. package/ui/components/ui/SlideOverFromRight.tsx +86 -0
  152. package/ui/components/vault/EnrollWizard.tsx +61 -13
  153. package/ui/components/vault/vaultErrorCopy.ts +3 -1
  154. package/ui/components/wallet/ActivityRow.tsx +227 -123
  155. package/ui/components/wallet/AmountInput.tsx +26 -8
  156. package/ui/components/wallet/AssetSwitcherDropdown.tsx +22 -2
  157. package/ui/components/wallet/Balance.tsx +42 -23
  158. package/ui/components/wallet/BiometricAdvisoryModal.tsx +16 -3
  159. package/ui/components/wallet/ContactActivityList.tsx +149 -0
  160. package/ui/components/wallet/ContactSigil.tsx +49 -0
  161. package/ui/components/wallet/EditPictureSheet.tsx +99 -0
  162. package/ui/components/wallet/FitAmount.tsx +148 -0
  163. package/ui/components/wallet/IconPickerSheet.tsx +168 -0
  164. package/ui/components/wallet/IdentifierRow.tsx +69 -0
  165. package/ui/components/wallet/ImportFromBackupPrompt.tsx +35 -13
  166. package/ui/components/wallet/ProfileButton.tsx +62 -0
  167. package/ui/components/wallet/UserAvatar.tsx +85 -0
  168. package/ui/components/wallet/avatarIcons.ts +122 -0
  169. package/ui/exportTransactions.ts +36 -4
  170. package/ui/hooks/useContactsStore.ts +10 -0
  171. package/ui/hooks/useExportWalletData.ts +25 -2
  172. package/ui/hooks/useMandala.ts +18 -1
  173. package/ui/hooks/useOnline.ts +65 -20
  174. package/ui/importDatabases.ts +339 -24
  175. package/ui/index.ts +33 -2
  176. package/ui/isImageUrl.ts +6 -0
  177. package/ui/printRecoveryShares.ts +9 -10
  178. package/ui/recoveryPrompts.ts +91 -0
  179. package/ui/resolveIdentity.ts +31 -9
  180. package/ui/screens/ConnectionsScreen.tsx +86 -19
  181. package/ui/screens/ContactScreen.tsx +289 -0
  182. package/ui/screens/ContactsScreen.tsx +373 -0
  183. package/ui/screens/IdentifierScreen.tsx +256 -0
  184. package/ui/screens/NewContactScreen.tsx +362 -0
  185. package/ui/screens/PairScreen.tsx +74 -2
  186. package/ui/screens/PayScreen.tsx +20 -7
  187. package/ui/screens/ProfileScreen.tsx +783 -0
  188. package/ui/screens/SettingsScreen.tsx +10 -4
  189. package/ui/screens/TransactionDetailScreen.tsx +419 -0
  190. package/ui/screens/TrustScreen.tsx +100 -5
  191. package/ui/screens/VaultScreen.tsx +410 -61
  192. package/ui/screens/VaultTransferScreen.tsx +59 -7
  193. package/ui/screens/WalletCheckScreen.tsx +17 -6
  194. package/ui/screens/WalletConfigScreen.tsx +124 -28
  195. package/ui/screens/WalletHomeScreen.tsx +640 -104
  196. package/ui/screens/detailActionKeys.ts +55 -0
  197. package/ui/tokenFormat.ts +44 -4
  198. package/ui/tokenStatus.ts +21 -0
  199. package/ui/txStatus.ts +48 -5
  200. package/core/storage/LocalStorageAdapter.ts +0 -58
@@ -0,0 +1,170 @@
1
+ /**
2
+ * restoreWallet — one attempt to turn a classified WalletSecret into a built,
3
+ * attested wallet: store it, drop the other secret kind, build (or rebuild),
4
+ * read the backup-replay outcome, attest. Used by both the mnemonic screen
5
+ * (`medium: 'phrase'`) and the scan-shares screen (`medium: 'shares'`);
6
+ * `recoverWallet.ts` wraps this in the retry/skip policy that needs prompts.
7
+ *
8
+ * SDK-FREE BY DESIGN: only `import type` reaches into `./secret` and
9
+ * `../services/vault/backupAttestation` — nothing here may load `@bsv/sdk`
10
+ * at runtime. `__tests__/recovery/sdkFree.test.ts` mocks `@bsv/sdk` to throw
11
+ * and requires this module to prove it. That is what lets a screen test
12
+ * (`__tests__/mnemonicSafety.test.tsx`, which mocks BOTH the toolbox package
13
+ * AND `@bsv/sdk` with closed object literals) wire in the REAL
14
+ * `restoreWallet` via `jest.requireActual` against its existing mocked deps.
15
+ *
16
+ * Write order — why it is exactly this, in this order:
17
+ *
18
+ * 1. Store the new secret FIRST. `setMnemonic`/`setRecoveredKey` can refuse
19
+ * (a declined biometric prompt) but never throw, so this is the one step
20
+ * whose "no" is ordinary, not exceptional — handled before anything else
21
+ * is touched.
22
+ * 2. Only once the store call returned `true` do we delete the OTHER secret
23
+ * kind. A refused biometric between these two writes must never leave the
24
+ * device with no secret at all: if step 1 says no, step 2 never runs, and
25
+ * whatever was already stored (if anything) is untouched. Once step 1
26
+ * succeeds, exactly one secret kind survives after this function returns
27
+ * — never both, never neither — which is what makes an auto-rebuild's
28
+ * "mnemonic wins over WIF" fallback pick the secret that was just
29
+ * imported instead of a stale one from a previous wallet.
30
+ * 3. Build. If a wallet is ALREADY built (`isWalletBuilt()`, read fresh here
31
+ * — never a value closed over earlier, because recoverWallet's retry loop
32
+ * spans awaits during which it can change), `rebuildWallet` is used
33
+ * instead of `buildWalletFromX`: the plain build fns silently no-op over
34
+ * an already-built wallet (by design, elsewhere), which would otherwise
35
+ * make "recover over an already-onboarded wallet" look like a success
36
+ * while nothing changed.
37
+ * 4. The backup-replay outcome (`getBackupRestore().phase`) is read ONLY
38
+ * when this attempt asked for a restore. The phase is a leftover from
39
+ * the LAST restore attempt and is not reset except by requesting another
40
+ * one — reading it after a `restore:false` attempt (the "skip" retry)
41
+ * would report a stale failure that this attempt never asked to happen.
42
+ * A `'failed'` phase here means the SECRET is stored but the wallet is
43
+ * NOT built: `WalletContext`'s restore block throws before its storage is
44
+ * published on a failed replay, destroys that never-published storage,
45
+ * and the outer build catch leaves the wallet unbuilt. So this reports
46
+ * `restore-failed` and skips attestation — there is no built wallet to
47
+ * attest to, and a wallet in this state has not proven it can be
48
+ * recovered from its backup either, so it should not be marked
49
+ * "backed up".
50
+ * 5. Attestation is NON-FATAL. By this point the wallet is already built and
51
+ * usable; a throw from `attest` (network blip, storage error) is
52
+ * console.warn'd and reported as `attested: false` rather than turning
53
+ * the whole attempt into a failure. The only consequence of an
54
+ * unrecorded attestation is that the backup reminder nags again later,
55
+ * which is the safe direction to fail in — silently swallowing a wallet
56
+ * that already exists would be worse.
57
+ *
58
+ * This module does NOT decide the retry/skip policy (that's
59
+ * `recoverWallet.ts`, which calls this in a loop), and does not touch UI,
60
+ * i18n, or navigation.
61
+ */
62
+ import type { WalletSecret } from './secret'
63
+ import type { BackupMedium } from '../services/vault/backupAttestation'
64
+
65
+ export interface RestoreWalletDeps {
66
+ setMnemonic(mnemonic: string): Promise<boolean>
67
+ setRecoveredKey(wif: string): Promise<boolean>
68
+ deleteMnemonic(): Promise<void>
69
+ deleteRecoveredKey(): Promise<void>
70
+ buildWalletFromMnemonic(mnemonic: string, opts?: { restoreFromBackup?: boolean }): Promise<void>
71
+ buildWalletFromRecoveredKey(wif: string, opts?: { restoreFromBackup?: boolean }): Promise<void>
72
+ rebuildWallet(opts?: { restoreFromBackup?: boolean }): Promise<void>
73
+ /** Read fresh on every call — a React state snapshot goes stale across the awaits inside. */
74
+ isWalletBuilt(): boolean
75
+ /**
76
+ * Is a secret already on this device? Used by `recoverWallet.ts`'s
77
+ * replace-wallet confirmation guard, BEFORE the first `restoreWallet`
78
+ * attempt — never read by `restoreWallet` itself, which stays a pure
79
+ * "one attempt" primitive with no policy of its own.
80
+ */
81
+ hasStoredIdentity(): Promise<boolean>
82
+ getBackupRestore(): {
83
+ phase: 'idle' | 'checking' | 'restoring' | 'restored' | 'no-backup' | 'failed'
84
+ error?: string
85
+ /**
86
+ * Set alongside a `'restored'` phase — true unless the replayed generation's newest
87
+ * entry could not be proven complete (see RemoteSyncReader.verifiedComplete). Absent for
88
+ * every other phase, and for a `'restored'` phase from a build that predates this field.
89
+ */
90
+ verified?: boolean
91
+ }
92
+ attest(identityKey: string, medium: BackupMedium): Promise<void>
93
+ }
94
+
95
+ export type RestoreHistory = 'restored' | 'no-backup' | 'skipped' | 'unknown'
96
+
97
+ export type RestoreOutcome =
98
+ | {
99
+ kind: 'ok'
100
+ identityKey: string
101
+ secret: WalletSecret
102
+ history: RestoreHistory
103
+ attested: boolean
104
+ /**
105
+ * True unless a restore actually happened (`history === 'restored'`) and its backup
106
+ * could not be proven complete (`getBackupRestore().verified === false`). Always true
107
+ * when nothing was restored — there is nothing to be unverified about.
108
+ */
109
+ verified: boolean
110
+ }
111
+ | { kind: 'biometric-refused'; secret: WalletSecret }
112
+ | { kind: 'restore-failed'; identityKey: string; secret: WalletSecret; error?: string }
113
+ | { kind: 'failed'; secret: WalletSecret; error: string }
114
+
115
+ /**
116
+ * One attempt. Never throws — anything thrown by `deps` is caught and
117
+ * reported as `{kind:'failed'}`.
118
+ */
119
+ export async function restoreWallet(
120
+ deps: RestoreWalletDeps,
121
+ secret: WalletSecret,
122
+ opts: { restore: boolean; medium: BackupMedium }
123
+ ): Promise<RestoreOutcome> {
124
+ try {
125
+ const stored =
126
+ secret.kind === 'mnemonic' ? await deps.setMnemonic(secret.mnemonic) : await deps.setRecoveredKey(secret.wif)
127
+
128
+ if (!stored) {
129
+ return { kind: 'biometric-refused', secret }
130
+ }
131
+
132
+ if (secret.kind === 'mnemonic') {
133
+ await deps.deleteRecoveredKey()
134
+ } else {
135
+ await deps.deleteMnemonic()
136
+ }
137
+
138
+ const buildOpts = { restoreFromBackup: opts.restore }
139
+ if (deps.isWalletBuilt()) {
140
+ await deps.rebuildWallet(buildOpts)
141
+ } else if (secret.kind === 'mnemonic') {
142
+ await deps.buildWalletFromMnemonic(secret.mnemonic, buildOpts)
143
+ } else {
144
+ await deps.buildWalletFromRecoveredKey(secret.wif, buildOpts)
145
+ }
146
+
147
+ let history: RestoreHistory = 'skipped'
148
+ let verified = true
149
+ if (opts.restore) {
150
+ const { phase, error, verified: restoreVerified } = deps.getBackupRestore()
151
+ if (phase === 'failed') {
152
+ return { kind: 'restore-failed', identityKey: secret.identityKey, secret, error }
153
+ }
154
+ history = phase === 'restored' || phase === 'no-backup' ? phase : 'unknown'
155
+ if (history === 'restored' && restoreVerified === false) verified = false
156
+ }
157
+
158
+ let attested = true
159
+ try {
160
+ await deps.attest(secret.identityKey, opts.medium)
161
+ } catch (err) {
162
+ attested = false
163
+ console.warn('[recovery] attestation failed (wallet is already built; backup reminder will nag again):', err)
164
+ }
165
+
166
+ return { kind: 'ok', identityKey: secret.identityKey, secret, history, attested, verified }
167
+ } catch (err) {
168
+ return { kind: 'failed', secret, error: err instanceof Error ? err.message : String(err) }
169
+ }
170
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * WalletSecret — the one input every recovery/creation orchestration module
3
+ * shares. `restoreWallet.ts`, `recoverWallet.ts` and `createWallet.ts` never
4
+ * touch `@bsv/sdk` directly (a jest guard enforces this, see
5
+ * `__tests__/recovery/sdkFree.test.ts`); they only see a `WalletSecret`, with
6
+ * its `identityKey` already computed HERE, at classification time.
7
+ *
8
+ * Why compute the identity key this early rather than reading it off the
9
+ * built wallet: `backupAttestation` needs an identity key to scope its
10
+ * record, and it has to be writable the moment a secret is stored — before
11
+ * the wallet's permissions manager exists to answer `getPublicKey`. A raw
12
+ * private key's own public key (for a WIF/hex import) and a derived
13
+ * `m/0'/0'` key's public key (for a mnemonic, matching every other place
14
+ * this repo derives a wallet's identity from a phrase) are both cheap,
15
+ * synchronous, sdk-only computations, so they happen here instead.
16
+ *
17
+ * This module does NOT decide storage, build order, or attestation — that is
18
+ * `restoreWallet.ts`'s job. It does not touch UI, i18n, or navigation.
19
+ */
20
+ import { Mnemonic, PrivateKey } from '@bsv/sdk'
21
+ import { recoverMnemonicWallet } from '../mnemonicWallet'
22
+ import { recoverSecretFromShares } from './shares'
23
+
24
+ export type WalletSecret =
25
+ | { kind: 'mnemonic'; mnemonic: string; identityKey: string }
26
+ | { kind: 'wif'; wif: string; identityKey: string }
27
+
28
+ const HEX_64 = /^[0-9a-fA-F]{64}$/
29
+
30
+ /**
31
+ * Classify raw text pasted or typed into the "import an existing wallet"
32
+ * input. Exactly two recognised shapes: a 64-hex-character private key, or a
33
+ * BIP39 recovery phrase (12-24 words, valid checksum). Anything else —
34
+ * including a hex string of the wrong length, which is NOT coerced or
35
+ * truncated — is `null`, and the caller shows a single "invalid input"
36
+ * message rather than a guess at what the user meant.
37
+ */
38
+ export function classifyImportInput(text: string): WalletSecret | null {
39
+ const trimmed = text.trim()
40
+ if (trimmed === '') return null
41
+
42
+ if (HEX_64.test(trimmed)) {
43
+ try {
44
+ const key = PrivateKey.fromHex(trimmed)
45
+ return { kind: 'wif', wif: key.toWif(), identityKey: key.toPublicKey().toString() }
46
+ } catch {
47
+ return null
48
+ }
49
+ }
50
+
51
+ try {
52
+ Mnemonic.fromString(trimmed)
53
+ } catch {
54
+ return null
55
+ }
56
+
57
+ return { kind: 'mnemonic', mnemonic: trimmed, identityKey: recoverMnemonicWallet(trimmed).identityKey }
58
+ }
59
+
60
+ /**
61
+ * Recombine a scanned/entered set of backup shares into a WalletSecret.
62
+ *
63
+ * Delegates the actual Shamir recombination and entropy-vs-legacy
64
+ * classification to `recoverSecretFromShares` (shares.ts) — this function's
65
+ * only job is to turn that result into the same `WalletSecret` shape
66
+ * `classifyImportInput` produces, so `restoreWallet` never has to know
67
+ * whether a secret came from typed text or scanned paper.
68
+ *
69
+ * `legacy: true` mirrors shares.ts's own distinction: shares split from a raw
70
+ * primary key (a wallet that itself has no mnemonic) recombine to a WIF, not
71
+ * a phrase, and the caller shows a different post-recovery notice for it.
72
+ *
73
+ * Throws exactly when `recoverSecretFromShares` throws — invalid shares or
74
+ * shares whose integrity tags disagree (mixed keys).
75
+ */
76
+ export function secretFromShares(shareStrings: string[]): { secret: WalletSecret; legacy: boolean } {
77
+ const recovered = recoverSecretFromShares(shareStrings)
78
+
79
+ if (recovered.kind === 'entropy') {
80
+ const mnemonic = Mnemonic.fromEntropy(recovered.entropy).toString()
81
+ return {
82
+ secret: { kind: 'mnemonic', mnemonic, identityKey: recoverMnemonicWallet(mnemonic).identityKey },
83
+ legacy: false
84
+ }
85
+ }
86
+
87
+ const key = new PrivateKey(recovered.primaryKey)
88
+ return {
89
+ secret: { kind: 'wif', wif: key.toWif(), identityKey: key.toPublicKey().toString() },
90
+ legacy: true
91
+ }
92
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Pure reducer for the scan-shares screen's accumulate/dedupe/threshold logic.
3
+ *
4
+ * Mirrors handleBarCodeScanned exactly, extracted so it can be unit-tested
5
+ * without a camera, a screen, or React: `lastRaw` is set on every non-ignored
6
+ * scan; on 'invalid'/'incompatible' it stays set, so scanning the exact same
7
+ * bad code twice in a row is a cheap, harmless 'ignored' (protects against a
8
+ * scanner firing multiple frames of the same code before the user moves the
9
+ * camera) rather than re-showing the same error. After 'added' it is cleared
10
+ * — scanning the just-accepted share again immediately is a genuine duplicate
11
+ * scan of a *different* share now in the collection, reported as
12
+ * 'incompatible' with issue 'duplicate', not silently swallowed as 'ignored'.
13
+ * 'complete' fires exactly once, the instant shares.length reaches the
14
+ * threshold (captured from the first accepted share) — never before, and the
15
+ * reducer does not suppress it if called again past that point (the screen
16
+ * stops scanning once it reacts to 'complete').
17
+ */
18
+ // Imports from shareParsing.ts, NOT shares.ts: shares.ts also frames/splits/
19
+ // recombines secrets via @bsv/sdk, and a value import of it would pull
20
+ // @bsv/sdk into this module's load — which the sdk-free guard test
21
+ // (__tests__/recovery/sdkFree.test.ts) proves never happens.
22
+ import { checkShareCompatibility, parseShare } from './shareParsing'
23
+ import type { ParsedShare, ShareCompatibilityIssue } from './shareParsing'
24
+
25
+ export interface ShareCollection {
26
+ shares: ParsedShare[]
27
+ threshold: number | null
28
+ lastRaw: string
29
+ }
30
+
31
+ export const emptyShareCollection: ShareCollection = Object.freeze({
32
+ shares: [],
33
+ threshold: null,
34
+ lastRaw: ''
35
+ })
36
+
37
+ export type ShareCollectEvent =
38
+ | { kind: 'ignored' } // same raw as the previous scan
39
+ | { kind: 'invalid' } // parseShare → null
40
+ | { kind: 'incompatible'; issue: ShareCompatibilityIssue }
41
+ | { kind: 'added'; scanned: number; needed: number }
42
+ | { kind: 'complete'; shareStrings: string[] }
43
+
44
+ export function collectShare(
45
+ c: ShareCollection,
46
+ raw: string
47
+ ): { collection: ShareCollection; event: ShareCollectEvent } {
48
+ if (raw === c.lastRaw) {
49
+ return { collection: c, event: { kind: 'ignored' } }
50
+ }
51
+
52
+ const parsed = parseShare(raw)
53
+ if (parsed === null) {
54
+ return { collection: { ...c, lastRaw: raw }, event: { kind: 'invalid' } }
55
+ }
56
+
57
+ const issue = checkShareCompatibility(parsed, c.shares)
58
+ if (issue !== null) {
59
+ return { collection: { ...c, lastRaw: raw }, event: { kind: 'incompatible', issue } }
60
+ }
61
+
62
+ const shares = [...c.shares, parsed]
63
+ const threshold = c.threshold ?? parsed.threshold
64
+ const next: ShareCollection = { shares, threshold, lastRaw: '' }
65
+
66
+ if (shares.length >= threshold) {
67
+ return { collection: next, event: { kind: 'complete', shareStrings: shares.map(s => s.raw) } }
68
+ }
69
+
70
+ return { collection: next, event: { kind: 'added', scanned: shares.length, needed: threshold } }
71
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Backup share PARSING and compatibility checks — split out of shares.ts.
3
+ *
4
+ * Deliberately has NO `@bsv/sdk` import. `shareCollector.ts` (the scan
5
+ * screen's pure reducer) needs exactly these functions and nothing else from
6
+ * shares.ts, and `shareCollector.ts` is one of the modules
7
+ * `__tests__/recovery/sdkFree.test.ts` proves never loads `@bsv/sdk` — a
8
+ * value import of the FULL shares.ts (which also frames/splits/recombines
9
+ * secrets via `PrivateKey`/`Hash`) would pull `@bsv/sdk` in transitively at
10
+ * module-load time even though shareCollector only calls these two
11
+ * functions. shares.ts re-exports everything here (`export * from
12
+ * './shareParsing'`) so every existing consumer of shares.ts — and, through
13
+ * it, `ui/backupShares.ts` — is unaffected.
14
+ */
15
+
16
+ export interface ParsedShare {
17
+ raw: string
18
+ x: string
19
+ y: string
20
+ threshold: number
21
+ integrity: string
22
+ }
23
+
24
+ /**
25
+ * Parse and validate a single backup share string.
26
+ * @returns Parsed share or null if invalid format
27
+ */
28
+ export function parseShare(shareString: string): ParsedShare | null {
29
+ const parts = shareString.trim().split('.')
30
+ if (parts.length !== 4) return null
31
+
32
+ const [x, y, thresholdStr, integrity] = parts
33
+ const threshold = Number(thresholdStr)
34
+
35
+ if (!x || !y || isNaN(threshold) || threshold < 2 || !integrity) return null
36
+
37
+ return { raw: shareString.trim(), x, y, threshold, integrity }
38
+ }
39
+
40
+ /** Why a newly scanned share cannot join the shares collected so far. */
41
+ export type ShareCompatibilityIssue = 'threshold-mismatch' | 'integrity-mismatch' | 'duplicate'
42
+
43
+ /**
44
+ * Validate that a new share is compatible with previously collected shares.
45
+ * Returns a code, not prose, so callers (screens) translate it themselves.
46
+ * @returns The issue code, or null if the share is compatible.
47
+ */
48
+ export function checkShareCompatibility(
49
+ newShare: ParsedShare,
50
+ existing: ParsedShare[]
51
+ ): ShareCompatibilityIssue | null {
52
+ if (existing.length === 0) return null
53
+
54
+ const first = existing[0]
55
+
56
+ if (newShare.threshold !== first.threshold) {
57
+ return 'threshold-mismatch'
58
+ }
59
+
60
+ if (newShare.integrity !== first.integrity) {
61
+ return 'integrity-mismatch'
62
+ }
63
+
64
+ // Check for duplicate (same x.y point)
65
+ const isDuplicate = existing.some(s => s.x === newShare.x && s.y === newShare.y)
66
+ if (isDuplicate) {
67
+ return 'duplicate'
68
+ }
69
+
70
+ return null
71
+ }
72
+
73
+ const COMPATIBILITY_MESSAGES: Record<ShareCompatibilityIssue, string> = {
74
+ 'threshold-mismatch': 'Threshold does not match previous shares',
75
+ 'integrity-mismatch': 'Integrity hash does not match — shares are from different keys',
76
+ duplicate: 'This share has already been scanned'
77
+ }
78
+
79
+ /**
80
+ * Validate that a new share is compatible with previously collected shares.
81
+ * @returns Error message string or null if valid
82
+ * @deprecated use checkShareCompatibility and translate the code in the UI layer
83
+ */
84
+ export function validateShareCompatibility(newShare: ParsedShare, existingShares: ParsedShare[]): string | null {
85
+ const issue = checkShareCompatibility(newShare, existingShares)
86
+ return issue === null ? null : COMPATIBILITY_MESSAGES[issue]
87
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Backup shares — Shamir 2-of-3 recovery paper.
3
+ *
4
+ * The secret being split is the MNEMONIC ENTROPY, per BRC-157, not the primary
5
+ * key at m/0'/0'. That derivation is hardened and one-way, so shares of it can
6
+ * restore spending authority but can never rebuild the phrase — and the vault
7
+ * key needs the phrase. Splitting the entropy makes paper and phrase two
8
+ * encodings of one secret.
9
+ *
10
+ * The split payload is always exactly 32 bytes:
11
+ *
12
+ * entropy(16) || sha256(entropy)[0..16]
13
+ *
14
+ * The tag exists so recovery can tell new paper from old WITHOUT a version
15
+ * marker on the printed page, which would break every sheet already in a
16
+ * drawer. Length cannot do that job: PrivateKey is a BigNumber and drops
17
+ * leading zero bytes (~1 payload in 256), and an imported 24-word phrase
18
+ * yields 32 bytes of entropy — the exact width of a legacy primary key.
19
+ *
20
+ * Do NOT try to validate the entropy branch by rebuilding a mnemonic and
21
+ * checking its BIP39 checksum. Mnemonic.fromEntropy COMPUTES that checksum, so
22
+ * it accepts any 16 bytes and can never reject a misclassification.
23
+ *
24
+ * Parsing and compatibility-checking a share string needs none of this
25
+ * module's `@bsv/sdk` use, so that half lives in `shareParsing.ts` instead
26
+ * (re-exported below, unchanged for every existing caller) — it is the half
27
+ * `shareCollector.ts`'s pure reducer imports, and `shareCollector.ts` is one
28
+ * of the modules the sdk-free guard test proves never loads `@bsv/sdk`.
29
+ */
30
+
31
+ import { PrivateKey, Hash } from '@bsv/sdk'
32
+
33
+ export * from './shareParsing'
34
+ import type { ParsedShare } from './shareParsing'
35
+
36
+ // ── Payload framing ──────────────────────────────────────────────────────────
37
+
38
+ /** Entropy of a 12-word BIP39 phrase. The only width v2 shares support. */
39
+ export const ENTROPY_BYTES = 16
40
+ /** Fixed width of the split secret. Never varies, never inferred. */
41
+ export const PAYLOAD_BYTES = 32
42
+
43
+ /** What a recombined payload turned out to be. */
44
+ export type RecoveredSecret = { kind: 'entropy'; entropy: number[] } | { kind: 'legacy'; primaryKey: number[] }
45
+
46
+ /** Wrap 16 bytes of entropy in the tagged 32-byte payload. */
47
+ export function frameEntropy(entropy: number[]): number[] {
48
+ if (entropy.length !== ENTROPY_BYTES) {
49
+ throw new Error(`frameEntropy: expected ${ENTROPY_BYTES} bytes, got ${entropy.length}`)
50
+ }
51
+ return [...entropy, ...Hash.sha256(entropy).slice(0, PAYLOAD_BYTES - ENTROPY_BYTES)]
52
+ }
53
+
54
+ /**
55
+ * Restore a recombined payload to full width.
56
+ *
57
+ * Shamir recombination yields a PrivateKey, whose toArray() drops leading zero
58
+ * bytes. Without this pad, roughly one payload in 256 decodes short and fails
59
+ * to match anything.
60
+ */
61
+ export function padPayload(bytes: number[]): number[] {
62
+ if (bytes.length > PAYLOAD_BYTES) {
63
+ throw new Error(`padPayload: payload exceeds ${PAYLOAD_BYTES} bytes`)
64
+ }
65
+ return [...new Array(PAYLOAD_BYTES - bytes.length).fill(0), ...bytes]
66
+ }
67
+
68
+ /** Decide whether a recombined payload is framed entropy or a legacy key. */
69
+ export function classifyPayload(raw: number[]): RecoveredSecret {
70
+ const payload = padPayload(raw)
71
+ const entropy = payload.slice(0, ENTROPY_BYTES)
72
+ const tag = payload.slice(ENTROPY_BYTES)
73
+ const expected = Hash.sha256(entropy).slice(0, PAYLOAD_BYTES - ENTROPY_BYTES)
74
+
75
+ return tag.every((b, i) => b === expected[i]) ? { kind: 'entropy', entropy } : { kind: 'legacy', primaryKey: payload }
76
+ }
77
+
78
+ // ── Share generation ─────────────────────────────────────────────────────────
79
+
80
+ /**
81
+ * Split mnemonic entropy into backup shares (the current format).
82
+ * @param entropy 16 bytes, from Mnemonic.toEntropy()
83
+ * @returns Share strings in the format base58(x).base58(y).threshold.integrity
84
+ */
85
+ export function generateEntropyShares(entropy: number[], threshold: number = 2, totalShares: number = 3): string[] {
86
+ return new PrivateKey(frameEntropy(entropy)).toBackupShares(threshold, totalShares)
87
+ }
88
+
89
+ /**
90
+ * Split a raw private key (the legacy format).
91
+ *
92
+ * Still reachable for wallets that were themselves restored from legacy paper
93
+ * and therefore have no mnemonic to frame. Removing it would leave that cohort
94
+ * with no way to back up at all; the tag check routes their shares back to the
95
+ * legacy branch on recovery, so this stays self-consistent.
96
+ */
97
+ export function generateLegacyKeyShares(
98
+ privateKeyBytes: number[],
99
+ threshold: number = 2,
100
+ totalShares: number = 3
101
+ ): string[] {
102
+ return new PrivateKey(privateKeyBytes).toBackupShares(threshold, totalShares)
103
+ }
104
+
105
+ // ── Share validation ─────────────────────────────────────────────────────────
106
+ // ParsedShare, parseShare, ShareCompatibilityIssue, checkShareCompatibility and
107
+ // validateShareCompatibility live in shareParsing.ts and are re-exported above.
108
+
109
+ /**
110
+ * Recombine shares and say what came out.
111
+ * @param shareStrings At least `threshold` raw share strings
112
+ * @throws If the shares are invalid or their integrity hashes disagree
113
+ */
114
+ export function recoverSecretFromShares(shareStrings: string[]): RecoveredSecret {
115
+ return classifyPayload(Array.from(PrivateKey.fromBackupShares(shareStrings).toArray()))
116
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * useRecoveryDeps — wires the plain `RestoreWalletDeps & CreateWalletDeps`
3
+ * orchestration modules (restoreWallet, recoverWallet, createWallet) to this
4
+ * app's real providers: `useWallet()` for the build/rebuild/status surface,
5
+ * `useLocalStorage()` for the secret store, `backupAttestation` for the raw
6
+ * writers (per the design's "keep the raw writers" decision —
7
+ * `recordBackupAttestation` stays unused), and `generateMnemonicWallet` for
8
+ * the create path's generator.
9
+ *
10
+ * `isWalletBuilt` is `getWalletBuilt`, not `walletBuilt`: the orchestration
11
+ * modules read it fresh across their internal `await`s (see restoreWallet.ts
12
+ * and createWallet.ts's own docs for why), and only the ref-backed getter can
13
+ * answer that — a captured `walletBuilt` boolean would be whatever it was at
14
+ * the render that produced this deps object, not "right now".
15
+ *
16
+ * Memoised on the individual function identities from each provider, NOT on
17
+ * the provider's return object — `useWallet()`/`useLocalStorage()` are
18
+ * plain `useContext` reads that hand back a fresh object every render even
19
+ * when nothing inside it changed, so depending on the objects themselves
20
+ * would rebuild (and hand every consumer a new-identity) deps object on
21
+ * every render of whatever calls this hook.
22
+ */
23
+ import { useMemo } from 'react'
24
+ import { useWallet } from '../context/WalletContext'
25
+ import { useLocalStorage } from '../context/LocalStorageProvider'
26
+ import { backupAttestation } from '../services/vault/backupAttestation'
27
+ import { generateMnemonicWallet } from '../mnemonicWallet'
28
+ import type { RestoreWalletDeps } from './restoreWallet'
29
+ import type { CreateWalletDeps } from './createWallet'
30
+
31
+ export function useRecoveryDeps(): RestoreWalletDeps & CreateWalletDeps {
32
+ const wallet = useWallet()
33
+ const local = useLocalStorage()
34
+
35
+ const { setMnemonic, setRecoveredKey, deleteMnemonic, deleteRecoveredKey, hasStoredIdentity, createMnemonic } = local
36
+ const { buildWalletFromMnemonic, buildWalletFromRecoveredKey, rebuildWallet, getWalletBuilt, getBackupRestore } =
37
+ wallet
38
+
39
+ return useMemo(
40
+ () => ({
41
+ setMnemonic,
42
+ setRecoveredKey,
43
+ deleteMnemonic,
44
+ deleteRecoveredKey,
45
+ hasStoredIdentity,
46
+ createMnemonic,
47
+ buildWalletFromMnemonic,
48
+ buildWalletFromRecoveredKey,
49
+ rebuildWallet,
50
+ isWalletBuilt: getWalletBuilt,
51
+ getBackupRestore,
52
+ attest: backupAttestation.set,
53
+ markPending: backupAttestation.markPending,
54
+ generate: generateMnemonicWallet
55
+ }),
56
+ [
57
+ setMnemonic,
58
+ setRecoveredKey,
59
+ deleteMnemonic,
60
+ deleteRecoveredKey,
61
+ hasStoredIdentity,
62
+ createMnemonic,
63
+ buildWalletFromMnemonic,
64
+ buildWalletFromRecoveredKey,
65
+ rebuildWallet,
66
+ getWalletBuilt,
67
+ getBackupRestore
68
+ ]
69
+ )
70
+ }
@@ -0,0 +1,52 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage'
2
+ import * as SecureStore from 'expo-secure-store'
3
+ import { arcApiTokenStorageKey } from '../constants'
4
+
5
+ /**
6
+ * XR-106: the custom ARC API token a holder can configure in
7
+ * WalletConfigScreen is a live credential — createServiceOptions puts it on
8
+ * `arcConfig.apiKey` and arcadeBroadcastProvider.ts sends it verbatim as
9
+ * `Authorization: Bearer <token>` on every broadcast to that endpoint — but it
10
+ * was persisted in plaintext AsyncStorage, which carries no at-rest
11
+ * encryption and is readable from an unencrypted device backup or a rooted /
12
+ * jailbroken device.
13
+ *
14
+ * This moves it into the platform SecureStore (iOS Keychain / Android
15
+ * Keystore), the same plain (no biometric gate, no keychainService override)
16
+ * pattern WalletConnectionContext already uses for its paired-session
17
+ * sequence counters — this is a non-Vault, non-signing service-config value,
18
+ * so it does not need the KEK-wrapped envelope scheme that protects wallet
19
+ * root secrets.
20
+ *
21
+ * Both functions also fold in a one-time migration of whatever a pre-fix
22
+ * build already left behind in plaintext AsyncStorage under the same key, so
23
+ * an existing configured token keeps working and is wiped from the
24
+ * unencrypted store on the very next read or write rather than sitting there
25
+ * indefinitely.
26
+ */
27
+ export async function getArcApiToken(network: string): Promise<string | null> {
28
+ const key = arcApiTokenStorageKey(network)
29
+ const legacy = await AsyncStorage.getItem(key)
30
+ const secure = await SecureStore.getItemAsync(key)
31
+ if (legacy === null) return secure
32
+ // A plaintext copy survived from before this fix (or from some other bug) —
33
+ // erase it unconditionally. A value already in SecureStore is authoritative
34
+ // over a stale plaintext one; only promote the legacy value when SecureStore
35
+ // has nothing yet.
36
+ await AsyncStorage.removeItem(key)
37
+ if (secure !== null) return secure
38
+ await SecureStore.setItemAsync(key, legacy)
39
+ return legacy
40
+ }
41
+
42
+ export async function setArcApiToken(network: string, token: string | null): Promise<void> {
43
+ const key = arcApiTokenStorageKey(network)
44
+ // Always clear any plaintext copy, whether or not one exists, so this
45
+ // function alone is enough to close out a legacy value.
46
+ await AsyncStorage.removeItem(key)
47
+ if (token) {
48
+ await SecureStore.setItemAsync(key, token)
49
+ } else {
50
+ await SecureStore.deleteItemAsync(key)
51
+ }
52
+ }