@bsv/expo-wallet-toolbox 0.21.0 → 0.23.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.
- package/CHANGELOG.md +222 -0
- package/README.md +82 -13
- package/core/bridge/BrowserBridgeProvider.tsx +273 -0
- package/core/bridge/bindings.ts +459 -0
- package/core/bridge/conformance.ts +222 -0
- package/core/bridge/consent.ts +494 -0
- package/core/bridge/consentSheetSource.ts +98 -0
- package/core/bridge/dispatcher.ts +621 -0
- package/core/bridge/inbox.ts +464 -0
- package/core/bridge/index.ts +48 -0
- package/core/bridge/loopback/cors.ts +57 -0
- package/core/bridge/loopback/endpoints.ts +11 -0
- package/core/bridge/loopback/hostCheck.ts +25 -0
- package/core/bridge/loopback/index.ts +7 -0
- package/core/bridge/loopback/launchProof.ts +166 -0
- package/core/bridge/loopback/router.ts +770 -0
- package/core/bridge/loopback/routerTypes.ts +115 -0
- package/core/bridge/loopback/status.ts +52 -0
- package/core/bridge/memoryInboxStore.ts +222 -0
- package/core/bridge/permissionPolicy.ts +247 -0
- package/core/bridge/policy.ts +72 -0
- package/core/bridge/protocol/base64url.ts +64 -0
- package/core/bridge/protocol/connectionError.ts +79 -0
- package/core/bridge/protocol/constants.ts +21 -0
- package/core/bridge/protocol/continuity.ts +21 -0
- package/core/bridge/protocol/descriptor.ts +395 -0
- package/core/bridge/protocol/envelopes.ts +188 -0
- package/core/bridge/protocol/errorCodec.ts +164 -0
- package/core/bridge/protocol/json.ts +237 -0
- package/core/bridge/protocol/limits.ts +43 -0
- package/core/bridge/protocol/methods.ts +55 -0
- package/core/bridge/protocol/origin.ts +130 -0
- package/core/bridge/runtime.ts +642 -0
- package/core/bridge/runtimeFlags.ts +34 -0
- package/core/bridge/testing/conformanceCases.ts +149 -0
- package/core/bridge/testing/pageClient.ts +44 -0
- package/core/bridge/unverifiedManager.ts +97 -0
- package/core/bridge/unverifiedOriginator.ts +79 -0
- package/core/config.tsx +1 -16
- package/core/contacts/contactActivity.ts +48 -28
- package/core/contacts/contactsStore.ts +2 -2
- package/core/context/WalletConnectionContext.tsx +7 -1
- package/core/context/WalletContext.tsx +420 -348
- package/core/context/sessionTeardown.ts +46 -0
- package/core/demo/demoAssets.ts +8 -10
- package/core/demo/demoLedger.ts +32 -38
- package/core/demo/demoMandalaRuntime.ts +67 -49
- package/core/demo/index.ts +1 -1
- package/core/hooks/usePermissionQueue.ts +89 -34
- package/core/i18n/translations.tsx +983 -12
- package/core/index.ts +70 -37
- package/core/localpay/build.ts +110 -569
- package/core/localpay/codec.ts +190 -93
- package/core/localpay/pending.ts +217 -202
- package/core/localpay/session.ts +99 -25
- package/core/localpay/types.ts +6 -5
- package/core/localpay/verify.ts +118 -173
- package/core/mandala/abortGuard.ts +97 -120
- package/core/mandala/accessPolicy.ts +133 -0
- package/core/mandala/assets.ts +370 -0
- package/core/mandala/colorGuard.ts +178 -0
- package/core/mandala/colorModule.ts +82 -0
- package/core/mandala/createRuntime.ts +483 -2392
- package/core/mandala/handle.ts +694 -0
- package/core/mandala/kvStore.ts +105 -0
- package/core/mandala/nearby.ts +185 -0
- package/core/mandala/receipt.ts +121 -0
- package/core/mandala/runtime.ts +166 -312
- package/core/mandala/settle.ts +540 -0
- package/core/mandala/transferJournal.ts +395 -0
- package/core/mandala/types.ts +61 -311
- package/core/networks.ts +5 -5
- package/core/offline/cancelParked.ts +80 -63
- package/core/offline/payerHold.ts +52 -118
- package/core/parsePeerPayURI.ts +25 -12
- package/core/pay/rails/handle.ts +15 -14
- package/core/pay/rails/index.ts +5 -3
- package/core/pay/rails/nearby.ts +25 -87
- package/core/profiles/assertProfileEmpty.ts +19 -10
- package/core/services/autoApprovePolicy.ts +7 -1
- package/core/services/capWalletArgs.ts +2 -1
- package/core/services/permissionPrompts.ts +132 -0
- package/core/services/signingPermissionPolicy.ts +230 -2
- package/core/services/vault/guard.ts +15 -4
- package/core/services/walletArgLimits.ts +17 -2
- package/core/storage/StorageExpoSQLite.ts +93 -229
- package/core/storage/encryptedDbImage.ts +325 -0
- package/core/storage/methods/processOfflineActions.ts +86 -136
- package/core/storage/schema/createTables.ts +9 -184
- package/core/toolboxConfig.ts +18 -1
- package/package.json +9 -8
- package/ui/bridgeSheet/ContextRelay.tsx +86 -0
- package/ui/bridgeSheet/relayedContexts.ts +21 -0
- package/ui/components/pay/AssetPicker.tsx +2 -2
- package/ui/components/pay/HandleReceive.tsx +4 -4
- package/ui/components/pay/NearbyFlow.tsx +324 -239
- package/ui/components/pay/RequestHub.tsx +10 -0
- package/ui/components/pay/UniversalSend.tsx +31 -28
- package/ui/components/pay/useRecipientInput.ts +2 -2
- package/ui/components/ui/PermissionSheet.tsx +625 -315
- package/ui/components/ui/Sheet.tsx +59 -7
- package/ui/components/ui/colorPrompt.ts +236 -0
- package/ui/components/ui/sheetResumeSignal.ts +19 -0
- package/ui/components/wallet/AmountInput.tsx +9 -6
- package/ui/components/wallet/AssetAmount.tsx +6 -6
- package/ui/components/wallet/AssetSwitcherDropdown.tsx +26 -7
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ContactActivityList.tsx +10 -13
- package/ui/components/wallet/tokenEviction.ts +9 -9
- package/ui/exportDatabases.ts +94 -5
- package/ui/hooks/useExportWalletData.ts +37 -24
- package/ui/hooks/useMandala.ts +6 -6
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/importDatabases.ts +124 -29
- package/ui/index.ts +4 -0
- package/ui/screens/PayScreen.tsx +14 -20
- package/ui/screens/SettingsScreen.tsx +3 -1
- package/ui/screens/WalletCheckScreen.tsx +7 -2
- package/ui/screens/WalletConfigScreen.tsx +13 -1
- package/ui/screens/WalletHomeScreen.tsx +40 -14
- package/ui/screens/tokenRowTitle.ts +28 -15
- package/ui/tokenFormat.ts +133 -69
- package/ui/tokenStatus.ts +5 -8
- package/core/localpay/settlementAck.ts +0 -155
- package/core/mandala/basketMigration.ts +0 -166
- package/core/mandala/bundle.ts +0 -244
- package/core/mandala/drain.ts +0 -754
- package/core/mandala/inboxPrehold.ts +0 -193
- package/core/mandala/permissionModule.ts +0 -931
- package/core/mandala/resendTransfer.ts +0 -178
- package/core/mandala/settlementStore.ts +0 -434
- package/core/mandala/token.ts +0 -45
- package/core/offline/tokenFrames.ts +0 -197
package/ui/exportDatabases.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { Platform } from 'react-native'
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
type StorageExpoSQLite,
|
|
4
|
+
type DbExportWallet,
|
|
5
|
+
type ByteSink,
|
|
6
|
+
type ByteSource,
|
|
7
|
+
parseDbFilename,
|
|
8
|
+
encryptDbImage,
|
|
9
|
+
ENCRYPTED_DB_EXTENSION
|
|
10
|
+
} from '@bsv/expo-wallet-toolbox'
|
|
3
11
|
|
|
4
12
|
/**
|
|
5
13
|
* expo-file-system and expo-sharing both ship untransformed ESM/raw-TS
|
|
@@ -39,16 +47,40 @@ function exportFilename(dbName: string): string {
|
|
|
39
47
|
return dbName.replace(/\.db$/, `-${ts}.db`)
|
|
40
48
|
}
|
|
41
49
|
|
|
50
|
+
export interface ExportWalletDatabaseOptions {
|
|
51
|
+
/**
|
|
52
|
+
* Encrypt the file to this wallet (`wallet.encrypt`, counterparty `self`)
|
|
53
|
+
* so only the same wallet can import it again. Off by default: the plain
|
|
54
|
+
* `.db` is still useful for development (open it in any SQLite browser).
|
|
55
|
+
*/
|
|
56
|
+
encrypt?: boolean
|
|
57
|
+
/** Required with `encrypt`: the wallet whose keys wrap the file key. */
|
|
58
|
+
wallet?: DbExportWallet
|
|
59
|
+
/** The admin originator, so the wrap never raises a permission prompt. */
|
|
60
|
+
originator?: string
|
|
61
|
+
/** Fraction (0..1) of the encryption done, for a progress indicator. */
|
|
62
|
+
onProgress?: (fraction: number) => void
|
|
63
|
+
}
|
|
64
|
+
|
|
42
65
|
/**
|
|
43
66
|
* Exports the currently active wallet database as a timestamped `.db` file
|
|
44
|
-
*
|
|
67
|
+
* (or, with `encrypt: true`, a `.db.enc` file) and presents the OS share
|
|
68
|
+
* dialogue so the user can save or send it.
|
|
45
69
|
*
|
|
46
|
-
*
|
|
47
|
-
* to avoid filesystem permission issues with the
|
|
70
|
+
* Plain export: on iOS the file is copied from disk; on Android
|
|
71
|
+
* `serializeAsync` is used to avoid filesystem permission issues with the
|
|
72
|
+
* native database directory.
|
|
48
73
|
*
|
|
49
74
|
* Returns the number of database files exported (0 or 1).
|
|
50
75
|
*/
|
|
51
|
-
export async function exportAllWalletDatabases(
|
|
76
|
+
export async function exportAllWalletDatabases(
|
|
77
|
+
storage: StorageExpoSQLite | null,
|
|
78
|
+
opts: ExportWalletDatabaseOptions = {}
|
|
79
|
+
): Promise<number> {
|
|
80
|
+
if (opts.encrypt) {
|
|
81
|
+
return exportEncrypted(storage, opts)
|
|
82
|
+
}
|
|
83
|
+
|
|
52
84
|
if (Platform.OS === 'android') {
|
|
53
85
|
return exportAndroid(storage)
|
|
54
86
|
}
|
|
@@ -56,6 +88,63 @@ export async function exportAllWalletDatabases(storage: StorageExpoSQLite | null
|
|
|
56
88
|
return exportIOS(storage)
|
|
57
89
|
}
|
|
58
90
|
|
|
91
|
+
/** A `file://` URI as the plain filesystem path SQLite wants. */
|
|
92
|
+
function nativePath(uri: string): string {
|
|
93
|
+
return decodeURI(uri.replace(/^file:\/\//, ''))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Encrypted export, on both platforms. `VACUUM INTO` writes a consistent,
|
|
98
|
+
* compacted snapshot of the live database (WAL included, concurrent writers
|
|
99
|
+
* unaffected) to a temp file on the native side, which is then encrypted a
|
|
100
|
+
* chunk at a time in native AES — the database is never held whole in JS
|
|
101
|
+
* memory. The plaintext snapshot lives only in the app's own cache and is
|
|
102
|
+
* deleted with the temp directory whether or not the share succeeds.
|
|
103
|
+
*/
|
|
104
|
+
async function exportEncrypted(storage: StorageExpoSQLite | null, opts: ExportWalletDatabaseOptions): Promise<number> {
|
|
105
|
+
if (!storage?.db) return 0
|
|
106
|
+
if (!opts.wallet) throw new Error('Encrypted export needs the wallet')
|
|
107
|
+
|
|
108
|
+
const { File, Directory, Paths, FileMode } = loadExpoFileSystem()
|
|
109
|
+
const { shareAsync } = loadExpoSharing()
|
|
110
|
+
|
|
111
|
+
const outName = exportFilename(storage.dbName).replace(/\.db$/, ENCRYPTED_DB_EXTENSION)
|
|
112
|
+
const tempDir = new Directory(Paths.cache, 'bsv-wallet-export')
|
|
113
|
+
if (tempDir.exists) tempDir.delete()
|
|
114
|
+
tempDir.create({ intermediates: true })
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
const snapshot = new File(tempDir, 'snapshot.db')
|
|
118
|
+
const snapshotPath = nativePath(snapshot.uri).replace(/'/g, "''")
|
|
119
|
+
await storage.db.execAsync(`VACUUM INTO '${snapshotPath}'`)
|
|
120
|
+
|
|
121
|
+
const outFile = new File(tempDir, outName)
|
|
122
|
+
outFile.create()
|
|
123
|
+
const reader = snapshot.open(FileMode.ReadOnly)
|
|
124
|
+
const writer = outFile.open(FileMode.WriteOnly)
|
|
125
|
+
try {
|
|
126
|
+
const src: ByteSource = { size: reader.size ?? snapshot.size, read: n => reader.readBytes(n) }
|
|
127
|
+
const sink: ByteSink = { write: b => writer.writeBytes(b) }
|
|
128
|
+
await encryptDbImage(opts.wallet, src, sink, { originator: opts.originator, onProgress: opts.onProgress })
|
|
129
|
+
} finally {
|
|
130
|
+
reader.close()
|
|
131
|
+
writer.close()
|
|
132
|
+
}
|
|
133
|
+
snapshot.delete()
|
|
134
|
+
|
|
135
|
+
await shareAsync(outFile.uri, {
|
|
136
|
+
mimeType: 'application/octet-stream',
|
|
137
|
+
dialogTitle: outName
|
|
138
|
+
})
|
|
139
|
+
} finally {
|
|
140
|
+
try {
|
|
141
|
+
tempDir.delete()
|
|
142
|
+
} catch {}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return 1
|
|
146
|
+
}
|
|
147
|
+
|
|
59
148
|
async function exportIOS(storage: StorageExpoSQLite | null): Promise<number> {
|
|
60
149
|
if (!storage?.db?.databasePath) return 0
|
|
61
150
|
|
|
@@ -8,41 +8,54 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Lifted from WalletConfigScreen.handleExportData so both screens share one
|
|
10
10
|
* implementation: one export at a time, `exporting` for the spinner, failures
|
|
11
|
-
*
|
|
11
|
+
* shown as an error toast (a dismissed share sheet resolves, so is not one).
|
|
12
12
|
*
|
|
13
|
-
* XR-086:
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* prompt.
|
|
13
|
+
* XR-086: the export is encrypted by default — `wallet.encrypt` (counterparty
|
|
14
|
+
* `self`, through the permissions manager as the admin originator, so no
|
|
15
|
+
* prompt) wraps a per-file AES key, so only this wallet can import it again.
|
|
16
|
+
* `exportData({ encrypt: false })` still writes the raw SQLite image, for
|
|
17
|
+
* development builds that want to open it in a SQLite browser. The
|
|
18
|
+
* confirmation alert that used to precede the share sheet was removed by
|
|
19
|
+
* product decision: the tap goes straight to the native save prompt.
|
|
21
20
|
*/
|
|
22
21
|
import { useCallback, useRef, useState } from 'react'
|
|
23
22
|
import { useWallet } from '@bsv/expo-wallet-toolbox'
|
|
24
23
|
import { exportAllWalletDatabases } from '../exportDatabases'
|
|
24
|
+
import { showToast } from '../components/ui/Toast'
|
|
25
25
|
|
|
26
|
-
export function useExportWalletData(): {
|
|
27
|
-
|
|
26
|
+
export function useExportWalletData(): {
|
|
27
|
+
exportData: (opts?: { encrypt?: boolean }) => Promise<void>
|
|
28
|
+
exporting: boolean
|
|
29
|
+
} {
|
|
30
|
+
const { storage, managers, adminOriginator } = useWallet()
|
|
28
31
|
const [exporting, setExporting] = useState(false)
|
|
29
32
|
// A ref, not the state: two taps in the same tick both see `exporting ===
|
|
30
33
|
// false` in their closure, and the second must still be refused.
|
|
31
34
|
const inFlightRef = useRef(false)
|
|
32
35
|
|
|
33
|
-
const exportData = useCallback(
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
36
|
+
const exportData = useCallback(
|
|
37
|
+
async ({ encrypt = true }: { encrypt?: boolean } = {}) => {
|
|
38
|
+
if (inFlightRef.current) return
|
|
39
|
+
inFlightRef.current = true
|
|
40
|
+
setExporting(true)
|
|
41
|
+
try {
|
|
42
|
+
await exportAllWalletDatabases(
|
|
43
|
+
storage,
|
|
44
|
+
encrypt ? { encrypt, wallet: managers.permissionsManager, originator: adminOriginator } : {}
|
|
45
|
+
)
|
|
46
|
+
} catch (e) {
|
|
47
|
+
// A dismissed share sheet resolves rather than throws, so anything
|
|
48
|
+
// landing here is a real failure (no crypto backend, no wallet yet,
|
|
49
|
+
// the snapshot refused) the user would otherwise never hear about.
|
|
50
|
+
console.warn('[exportWalletData] Export failed:', e)
|
|
51
|
+
showToast(e instanceof Error ? e.message : String(e), { type: 'error' })
|
|
52
|
+
} finally {
|
|
53
|
+
inFlightRef.current = false
|
|
54
|
+
setExporting(false)
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
[storage, managers.permissionsManager, adminOriginator]
|
|
58
|
+
)
|
|
46
59
|
|
|
47
60
|
return { exportData, exporting }
|
|
48
61
|
}
|
package/ui/hooks/useMandala.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Everything token-shaped on a screen (a balance row, a picker option, an
|
|
5
5
|
* activity status, a refusal sentence) comes from `MandalaRuntime` and nothing
|
|
6
|
-
* else: the UI never talks to the overlay, the lib or the
|
|
6
|
+
* else: the UI never talks to the overlay, the lib or the transfer journal
|
|
7
7
|
* directly, so failure copy, journalling and state stay in one place
|
|
8
8
|
* (core/mandala/runtime.ts's own design rule).
|
|
9
9
|
*
|
|
@@ -35,7 +35,7 @@ import type {
|
|
|
35
35
|
TokenAssetStatus,
|
|
36
36
|
TokenBalance
|
|
37
37
|
} from '../../core/mandala/runtime'
|
|
38
|
-
import type {
|
|
38
|
+
import type { ColorTransferRow } from '../../core/mandala/types'
|
|
39
39
|
|
|
40
40
|
/**
|
|
41
41
|
* expo-router is required lazily rather than imported at module scope: this
|
|
@@ -103,20 +103,20 @@ export interface MandalaState {
|
|
|
103
103
|
balances: TokenBalance[] | null
|
|
104
104
|
/** Just the assets, for a picker. `[]` when nothing is held. */
|
|
105
105
|
assets: TokenAssetInfo[]
|
|
106
|
-
/** Non-terminal
|
|
107
|
-
stuck:
|
|
106
|
+
/** Non-terminal `color_transfers` rows past the stuck bound (FIX M) — the home badge. */
|
|
107
|
+
stuck: ColorTransferRow[]
|
|
108
108
|
/** True only while the FIRST read is outstanding; a refresh keeps the figures. */
|
|
109
109
|
loading: boolean
|
|
110
110
|
refresh: () => void
|
|
111
111
|
}
|
|
112
112
|
|
|
113
113
|
const EMPTY_ASSETS: TokenAssetInfo[] = []
|
|
114
|
-
const EMPTY_STUCK:
|
|
114
|
+
const EMPTY_STUCK: ColorTransferRow[] = []
|
|
115
115
|
|
|
116
116
|
export function useMandala(): MandalaState {
|
|
117
117
|
const runtime = useMandalaRuntime()
|
|
118
118
|
const [balances, setBalances] = useState<TokenBalance[] | null>(null)
|
|
119
|
-
const [stuck, setStuck] = useState<
|
|
119
|
+
const [stuck, setStuck] = useState<ColorTransferRow[]>(EMPTY_STUCK)
|
|
120
120
|
const [loading, setLoading] = useState(false)
|
|
121
121
|
const [nonce, setNonce] = useState(0)
|
|
122
122
|
const runtimeRef = useRef<MandalaRuntime | null>(runtime)
|
|
@@ -51,7 +51,9 @@ export function useSpendableBalance(): number | null {
|
|
|
51
51
|
const pm = managers?.permissionsManager
|
|
52
52
|
if (!pm) return
|
|
53
53
|
const { totalOutputs } = await pm.listOutputs({ basket: sdk.specOpWalletBalance }, adminOriginator)
|
|
54
|
-
|
|
54
|
+
// sdk 4 types `totalOutputs` as number | DecimalString (BRC-112 module
|
|
55
|
+
// balances); the satoshi wallet balance is always a safe integer.
|
|
56
|
+
total = Number(totalOutputs ?? 0)
|
|
55
57
|
}
|
|
56
58
|
if (cancelled) return
|
|
57
59
|
setBalance(prev => (prev?.key === cacheKey && prev.value === total ? prev : { key: cacheKey, value: total }))
|
package/ui/importDatabases.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { Platform } from 'react-native'
|
|
|
2
2
|
import * as SQLite from 'expo-sqlite'
|
|
3
3
|
import {
|
|
4
4
|
type StorageExpoSQLite,
|
|
5
|
+
type DbExportWallet,
|
|
5
6
|
i18n,
|
|
6
7
|
parseDbFilename,
|
|
7
8
|
getRegisteredDbs,
|
|
@@ -11,7 +12,10 @@ import {
|
|
|
11
12
|
prepareSqliteImageForDeserialize,
|
|
12
13
|
PENDING_KEY,
|
|
13
14
|
PENDING_SUMMARY_KEY,
|
|
14
|
-
createTables
|
|
15
|
+
createTables,
|
|
16
|
+
decryptDbImage,
|
|
17
|
+
EncryptedDbError,
|
|
18
|
+
ENCRYPTED_DB_EXTENSION
|
|
15
19
|
} from '@bsv/expo-wallet-toolbox'
|
|
16
20
|
import { showAlert } from './components/ui/AlertCard'
|
|
17
21
|
import { showToast } from './components/ui/Toast'
|
|
@@ -64,6 +68,38 @@ const MAX_FUTURE_SKEW_SECONDS = 300
|
|
|
64
68
|
*/
|
|
65
69
|
const MAX_IMPORT_BYTES = 256 * 1024 * 1024 // 256 MiB
|
|
66
70
|
|
|
71
|
+
/**
|
|
72
|
+
* An encrypted backup never passes through JS memory whole — it is decrypted
|
|
73
|
+
* a chunk at a time to a temp file that SQLite opens directly — so its
|
|
74
|
+
* ceiling is about disk, not RAM: the cache holds the picked copy plus the
|
|
75
|
+
* decrypted one while the import runs.
|
|
76
|
+
*/
|
|
77
|
+
const MAX_ENCRYPTED_IMPORT_BYTES = 2 * 1024 * 1024 * 1024 // 2 GiB
|
|
78
|
+
|
|
79
|
+
export interface ImportWalletDatabaseOptions {
|
|
80
|
+
/** Required to import an encrypted (`.db.enc`) backup: the wallet that exported it. */
|
|
81
|
+
wallet?: DbExportWallet
|
|
82
|
+
/** The admin originator, so the key unwrap never raises a permission prompt. */
|
|
83
|
+
originator?: string
|
|
84
|
+
/** Fraction (0..1) of the decryption done, for a progress indicator. */
|
|
85
|
+
onProgress?: (fraction: number) => void
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A `file://` URI as the plain filesystem path SQLite wants. */
|
|
89
|
+
function nativePath(uri: string): string {
|
|
90
|
+
return decodeURI(uri.replace(/^file:\/\//, ''))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Best-effort removal of an encrypted import's picked copy and decrypted temp directory. */
|
|
94
|
+
function cleanupImportFiles(picked: { delete(): void }, tempDir: { exists: boolean; delete(): void }): void {
|
|
95
|
+
try {
|
|
96
|
+
picked.delete()
|
|
97
|
+
} catch {}
|
|
98
|
+
try {
|
|
99
|
+
if (tempDir.exists) tempDir.delete()
|
|
100
|
+
} catch {}
|
|
101
|
+
}
|
|
102
|
+
|
|
67
103
|
async function rejectAsUntrusted(): Promise<ImportResult> {
|
|
68
104
|
await showAlert({
|
|
69
105
|
title: i18n.t('import_untrusted_file'),
|
|
@@ -271,18 +307,27 @@ function buildUniqueTargetFilename(keySuffix: string, chain: string, baseTs: num
|
|
|
271
307
|
}
|
|
272
308
|
|
|
273
309
|
/**
|
|
274
|
-
* Let the user pick a wallet
|
|
275
|
-
*
|
|
276
|
-
* highest timestamp in its
|
|
310
|
+
* Let the user pick a wallet backup file — a plain `.db` or an encrypted
|
|
311
|
+
* `.db.enc` — and import it alongside any existing databases. The wallet
|
|
312
|
+
* context will use whichever database has the highest timestamp in its
|
|
313
|
+
* filename.
|
|
277
314
|
*
|
|
278
315
|
* Platform handling:
|
|
279
|
-
* -
|
|
316
|
+
* - Plain `.db`: reads the picked file as bytes, deserializes into an
|
|
280
317
|
* in-memory SQLite DB, opens a new file-backed DB with the target name,
|
|
281
318
|
* then uses backupDatabaseAsync to copy the data across. This avoids
|
|
282
319
|
* filesystem permission issues on Android.
|
|
320
|
+
* - Encrypted `.db.enc`: streams the picked file through native AES into a
|
|
321
|
+
* temp `.db` in the cache (one chunk in memory at a time), opens that
|
|
322
|
+
* file directly, and runs the same checks and backupDatabaseAsync copy.
|
|
323
|
+
* A file another wallet exported, or a damaged one, fails to decrypt and
|
|
324
|
+
* is refused as untrusted.
|
|
283
325
|
*/
|
|
284
|
-
export async function importWalletDatabase(
|
|
285
|
-
|
|
326
|
+
export async function importWalletDatabase(
|
|
327
|
+
storage: StorageExpoSQLite | null,
|
|
328
|
+
opts: ImportWalletDatabaseOptions = {}
|
|
329
|
+
): Promise<ImportResult> {
|
|
330
|
+
const { File, Directory, Paths, FileMode } = loadExpoFileSystem()
|
|
286
331
|
const DocumentPicker = loadDocumentPicker()
|
|
287
332
|
|
|
288
333
|
// ── 1. Pick file ──────────────────────────────────────────────────────────
|
|
@@ -297,18 +342,20 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
|
|
|
297
342
|
|
|
298
343
|
const asset = result.assets[0]
|
|
299
344
|
const pickedName = asset.name
|
|
345
|
+
const encrypted = pickedName.endsWith(ENCRYPTED_DB_EXTENSION)
|
|
346
|
+
const maxBytes = encrypted ? MAX_ENCRYPTED_IMPORT_BYTES : MAX_IMPORT_BYTES
|
|
300
347
|
|
|
301
348
|
// ── 1.5 Enforce a size ceiling ───────────────────────────────────────────
|
|
302
349
|
// Picker metadata is untrusted, but it is still the cheapest possible
|
|
303
350
|
// rejection — refuse before ever constructing a File or reading a byte
|
|
304
351
|
// (XR-087). A missing size is treated the same as an oversized one: fail
|
|
305
352
|
// closed rather than assume a small file.
|
|
306
|
-
if (asset.size == null || asset.size >
|
|
353
|
+
if (asset.size == null || asset.size > maxBytes) {
|
|
307
354
|
return rejectAsOversized(asset.uri)
|
|
308
355
|
}
|
|
309
356
|
|
|
310
357
|
// ── 2. Validate filename ──────────────────────────────────────────────────
|
|
311
|
-
const parsed = parseDbFilename(pickedName)
|
|
358
|
+
const parsed = parseDbFilename(encrypted ? pickedName.slice(0, -'.enc'.length) : pickedName)
|
|
312
359
|
if (!parsed) {
|
|
313
360
|
await showAlert({
|
|
314
361
|
title: i18n.t('import_invalid_file'),
|
|
@@ -365,22 +412,72 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
|
|
|
365
412
|
}
|
|
366
413
|
}
|
|
367
414
|
|
|
368
|
-
// ── 4.
|
|
415
|
+
// ── 4. Get the source image into SQLite ──────────────────────────────────
|
|
416
|
+
// Plain: the picked bytes, deserialized in memory. Encrypted: decrypted to
|
|
417
|
+
// a temp file first, then opened from disk.
|
|
369
418
|
const pickedFile = new File(asset.uri)
|
|
370
|
-
let
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
419
|
+
let openSource: () => Promise<SQLite.SQLiteDatabase>
|
|
420
|
+
let cleanup = () => {}
|
|
421
|
+
if (encrypted) {
|
|
422
|
+
const tempDir = new Directory(Paths.cache, 'bsv-wallet-import')
|
|
423
|
+
cleanup = () => cleanupImportFiles(pickedFile, tempDir)
|
|
424
|
+
if (!opts.wallet) {
|
|
425
|
+
return rejectAsUntrusted()
|
|
426
|
+
}
|
|
427
|
+
// The file system's byte count, not the picker's claim (XR-087).
|
|
428
|
+
if (pickedFile.size > MAX_ENCRYPTED_IMPORT_BYTES) {
|
|
429
|
+
return rejectAsOversized(asset.uri)
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
if (tempDir.exists) tempDir.delete()
|
|
433
|
+
tempDir.create({ intermediates: true })
|
|
434
|
+
const plainFile = new File(tempDir, 'import.db')
|
|
435
|
+
plainFile.create()
|
|
436
|
+
const reader = pickedFile.open(FileMode.ReadOnly)
|
|
437
|
+
const writer = plainFile.open(FileMode.WriteOnly)
|
|
438
|
+
try {
|
|
439
|
+
await decryptDbImage(
|
|
440
|
+
opts.wallet,
|
|
441
|
+
{ size: reader.size ?? pickedFile.size, read: n => reader.readBytes(n) },
|
|
442
|
+
{ write: b => writer.writeBytes(b) },
|
|
443
|
+
{ originator: opts.originator, onProgress: opts.onProgress }
|
|
444
|
+
)
|
|
445
|
+
} finally {
|
|
446
|
+
reader.close()
|
|
447
|
+
writer.close()
|
|
448
|
+
}
|
|
449
|
+
} catch (e: any) {
|
|
450
|
+
cleanup()
|
|
451
|
+
if (e instanceof EncryptedDbError && e.code !== 'no-native-crypto') {
|
|
452
|
+
console.warn('[importDatabases] Encrypted backup refused:', e.code, e.message)
|
|
453
|
+
return rejectAsUntrusted()
|
|
454
|
+
}
|
|
455
|
+
console.error('[importDatabases] Failed to decrypt picked file:', e.message)
|
|
456
|
+
showToast(e.message, { type: 'error' })
|
|
457
|
+
return { imported: false }
|
|
458
|
+
}
|
|
459
|
+
openSource = () => SQLite.openDatabaseAsync('import.db', undefined, nativePath(tempDir.uri))
|
|
460
|
+
} else {
|
|
461
|
+
let bytes: Uint8Array
|
|
462
|
+
try {
|
|
463
|
+
bytes = await pickedFile.bytes()
|
|
464
|
+
} catch (e: any) {
|
|
465
|
+
console.error('[importDatabases] Failed to read picked file:', e.message)
|
|
466
|
+
showToast(e.message, { type: 'error' })
|
|
467
|
+
return { imported: false }
|
|
468
|
+
}
|
|
378
469
|
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
470
|
+
// Picker-reported `asset.size` is untrusted metadata — re-check the actual
|
|
471
|
+
// byte count before it ever reaches WAL normalization/deserialization,
|
|
472
|
+
// which can allocate a second full-size copy on top of this one (XR-087).
|
|
473
|
+
if (bytes.length > MAX_IMPORT_BYTES) {
|
|
474
|
+
return rejectAsOversized(asset.uri)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// Exports of the WAL-mode wallet DB carry a WAL header, which the
|
|
478
|
+
// in-memory VFS cannot open (SQLITE_CANTOPEN), so the header is
|
|
479
|
+
// rewritten to rollback-journal mode first.
|
|
480
|
+
openSource = () => SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
|
|
384
481
|
}
|
|
385
482
|
|
|
386
483
|
// ── 5. Place the database via deserialize → backup ────────────────────────
|
|
@@ -389,11 +486,7 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
|
|
|
389
486
|
let untrusted = false
|
|
390
487
|
let targetFilename = ''
|
|
391
488
|
try {
|
|
392
|
-
|
|
393
|
-
// the WAL-mode wallet DB carry a WAL header, which the in-memory VFS
|
|
394
|
-
// cannot open (SQLITE_CANTOPEN), so the header is rewritten to
|
|
395
|
-
// rollback-journal mode first.
|
|
396
|
-
sourceDb = await SQLite.deserializeDatabaseAsync(prepareSqliteImageForDeserialize(bytes))
|
|
489
|
+
sourceDb = await openSource()
|
|
397
490
|
|
|
398
491
|
// Authenticate the image against the currently unlocked wallet BEFORE any
|
|
399
492
|
// of it is written to disk under an authoritative name: exactly one
|
|
@@ -437,7 +530,7 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
|
|
|
437
530
|
// backupDatabaseAsync just copied key_value_store verbatim, including
|
|
438
531
|
// any localpay_pending queue the source had — a record placed there by
|
|
439
532
|
// whoever wrote that file, never re-verified by processPending before
|
|
440
|
-
// it is drained into internalizeAction
|
|
533
|
+
// it is drained into internalizeAction. Quarantine at this
|
|
441
534
|
// boundary, before the copy is ever registered or read: an imported
|
|
442
535
|
// backup must never be able to seed the live queue (XR-081).
|
|
443
536
|
await destDb.runAsync('DELETE FROM key_value_store WHERE key IN (?, ?)', [PENDING_KEY, PENDING_SUMMARY_KEY])
|
|
@@ -476,6 +569,8 @@ export async function importWalletDatabase(storage: StorageExpoSQLite | null): P
|
|
|
476
569
|
try {
|
|
477
570
|
await destDb?.closeAsync()
|
|
478
571
|
} catch {}
|
|
572
|
+
// Neither the picked copy nor the decrypted plaintext outlives the import.
|
|
573
|
+
cleanup()
|
|
479
574
|
}
|
|
480
575
|
|
|
481
576
|
if (untrusted) {
|
package/ui/index.ts
CHANGED
|
@@ -219,3 +219,7 @@ export { AVATAR_ICON_GROUPS, type AvatarIconOption, type AvatarIconGroup } from
|
|
|
219
219
|
|
|
220
220
|
export { default as IconPickerSheet } from './components/wallet/IconPickerSheet'
|
|
221
221
|
export { default as EditPictureSheet, type EditPictureOption } from './components/wallet/EditPictureSheet'
|
|
222
|
+
|
|
223
|
+
// Android bridge sheet: relays the first React root's contexts to the sheet's second root.
|
|
224
|
+
export { ContextRelayPublisher, ContextRelaySubscriber, resetContextRelay } from './bridgeSheet/ContextRelay'
|
|
225
|
+
export { RELAYED_CONTEXTS } from './bridgeSheet/relayedContexts'
|
package/ui/screens/PayScreen.tsx
CHANGED
|
@@ -21,7 +21,7 @@ import { partitionQueueByGrace } from '../../core/offline/queueGrace'
|
|
|
21
21
|
import PaymentQrDisplay from '../components/pay/PaymentQrDisplay'
|
|
22
22
|
import UniversalSend, { type UniversalSendHandle } from '../components/pay/UniversalSend'
|
|
23
23
|
import type { PayStep } from '../components/pay/StepBar'
|
|
24
|
-
import RequestHub, { requestSatsFrom, type RequestMethod } from '../components/pay/RequestHub'
|
|
24
|
+
import RequestHub, { requestSatsFrom, requestUnitsFrom, type RequestMethod } from '../components/pay/RequestHub'
|
|
25
25
|
import NearbyFlow from '../components/pay/NearbyFlow'
|
|
26
26
|
import HandleReceive from '../components/pay/HandleReceive'
|
|
27
27
|
import AddressReceive from '../components/pay/AddressReceive'
|
|
@@ -164,7 +164,7 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
|
|
|
164
164
|
const satsParam = linkSats ?? Number(firstParam(params.sats))
|
|
165
165
|
const initialSats = Number.isFinite(satsParam) && satsParam > 0 ? Number(satsParam) : undefined
|
|
166
166
|
const initialTokenAmount = useMemo(
|
|
167
|
-
() => (linkAsset && linkAmount ? { assetId: linkAsset,
|
|
167
|
+
() => (linkAsset && linkAmount ? { assetId: linkAsset, units: linkAmount } : undefined),
|
|
168
168
|
[linkAsset, linkAmount]
|
|
169
169
|
)
|
|
170
170
|
// Memoized: useRecipientInput re-adopts initialTarget whenever its identity changes.
|
|
@@ -259,25 +259,19 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
|
|
|
259
259
|
* on the payee's own screen and binding the payer to that figure. The
|
|
260
260
|
* discriminated shape makes the unit impossible to lose.
|
|
261
261
|
*/
|
|
262
|
-
const request: { kind: 'bsv'; sats?: number } | { kind: 'token';
|
|
263
|
-
? { kind: 'token',
|
|
262
|
+
const request: { kind: 'bsv'; sats?: number } | { kind: 'token'; units?: bigint; assetId: string } = asset
|
|
263
|
+
? { kind: 'token', units: requestUnitsFrom(requestSats), assetId: asset.assetId }
|
|
264
264
|
: { kind: 'bsv', sats: requestSatsFrom(requestSats) }
|
|
265
265
|
const initialNearbyRequest = useMemo(
|
|
266
|
-
() =>
|
|
267
|
-
|
|
268
|
-
...(asset
|
|
266
|
+
() =>
|
|
267
|
+
asset
|
|
269
268
|
? {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
decimals: asset.decimals,
|
|
275
|
-
overlayUrl: asset.overlayUrl,
|
|
276
|
-
overlayIdentityKey: asset.overlayIdentityKey
|
|
277
|
-
}
|
|
269
|
+
// Exact token units (session v2 carries `a` as a decimal string);
|
|
270
|
+
// the session names no overlay, the payer uses its own (W6).
|
|
271
|
+
units: requestUnitsFrom(requestSats),
|
|
272
|
+
asset: { id: asset.assetId, label: asset.label, ticker: asset.ticker, decimals: asset.decimals }
|
|
278
273
|
}
|
|
279
|
-
: {}
|
|
280
|
-
}),
|
|
274
|
+
: { sats: requestSatsFrom(requestSats) },
|
|
281
275
|
[requestSats, asset]
|
|
282
276
|
)
|
|
283
277
|
// One camera raise per deep link; a cancelled advisory must not re-open it.
|
|
@@ -527,8 +521,8 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
|
|
|
527
521
|
// base units, and every satoshi-shaped prop below must not see them.
|
|
528
522
|
const sats = request.kind === 'bsv' ? request.sats : undefined
|
|
529
523
|
const requestedAmountText =
|
|
530
|
-
asset && request.kind === 'token' && request.
|
|
531
|
-
? (formatTokenAmountWithUnit(request.
|
|
524
|
+
asset && request.kind === 'token' && request.units !== undefined
|
|
525
|
+
? (formatTokenAmountWithUnit(request.units, asset) ?? undefined)
|
|
532
526
|
: undefined
|
|
533
527
|
switch (method) {
|
|
534
528
|
case 'get-nearby':
|
|
@@ -540,7 +534,7 @@ export function PayScreen({ dismissTo = '/' }: PayScreenProps = {}) {
|
|
|
540
534
|
<HandleReceive
|
|
541
535
|
initialSats={sats}
|
|
542
536
|
asset={asset ? { assetId: asset.assetId, ticker: asset.ticker, issuerName: asset.issuerName } : null}
|
|
543
|
-
|
|
537
|
+
requestedUnits={request.kind === 'token' ? request.units : undefined}
|
|
544
538
|
requestedAmountText={requestedAmountText}
|
|
545
539
|
assetMessageBoxUrl={selectedAssetStatus?.messageBoxUrl ?? null}
|
|
546
540
|
onBsvInstead={() => setSelectedAssetId(null)}
|
|
@@ -65,7 +65,9 @@ export function SettingsScreen() {
|
|
|
65
65
|
{ basket: sdk.specOpWalletBalance },
|
|
66
66
|
adminOriginator
|
|
67
67
|
)
|
|
68
|
-
|
|
68
|
+
// sdk 4 types `totalOutputs` as number | DecimalString (BRC-112 module
|
|
69
|
+
// balances); the satoshi wallet balance is always a safe integer.
|
|
70
|
+
const total = Number(totalOutputs ?? 0)
|
|
69
71
|
setAccountBalance(total)
|
|
70
72
|
setBalanceLoading(false)
|
|
71
73
|
await Promise.all([
|
|
@@ -164,9 +164,14 @@ function useWalletCheckPorts(): WalletCheckPorts {
|
|
|
164
164
|
},
|
|
165
165
|
reviewTokens: async () => {
|
|
166
166
|
if (!mandala?.available) return { settled: 0, removed: 0, unattested: 0 }
|
|
167
|
-
const { settled,
|
|
167
|
+
const { settled, pending, unreachable } = await mandala.reviewTokenHoldings()
|
|
168
168
|
if (unreachable) throw new Error('token overlay unreachable')
|
|
169
|
-
|
|
169
|
+
// 1Color (B7): the review is the host's settle pass plus a count of where every
|
|
170
|
+
// journal row stands. It removes nothing itself (a refused hand-over's
|
|
171
|
+
// coins come back through its own abort, counted nowhere here), so
|
|
172
|
+
// `removed` is 0 and never inflates freedCoins with history. Rows
|
|
173
|
+
// still waiting on the issuer are what the step reports for attention.
|
|
174
|
+
return { settled, removed: 0, unattested: pending }
|
|
170
175
|
},
|
|
171
176
|
checkProofs: async () => {
|
|
172
177
|
await runMonitorTask('CheckForProofs')
|
|
@@ -436,7 +436,10 @@ export function WalletConfigScreen({ hideLogout = false }: { hideLogout?: boolea
|
|
|
436
436
|
if (isImporting) return
|
|
437
437
|
setIsImporting(true)
|
|
438
438
|
try {
|
|
439
|
-
const result = await importWalletDatabase(storage
|
|
439
|
+
const result = await importWalletDatabase(storage, {
|
|
440
|
+
wallet: managers.permissionsManager,
|
|
441
|
+
originator: adminOriginator
|
|
442
|
+
})
|
|
440
443
|
if (result.imported) {
|
|
441
444
|
showToast(t('import_success'), { type: 'success' })
|
|
442
445
|
// Not restoreFromBackup: a raw db import already carries a complete
|
|
@@ -995,6 +998,15 @@ export function WalletConfigScreen({ hideLogout = false }: { hideLogout?: boolea
|
|
|
995
998
|
showChevron={false}
|
|
996
999
|
trailing={exporting ? <ActivityIndicator size="small" /> : undefined}
|
|
997
1000
|
/>
|
|
1001
|
+
{__DEV__ && (
|
|
1002
|
+
<ListRow
|
|
1003
|
+
label="Export Wallet Data (unencrypted)"
|
|
1004
|
+
icon="share-outline"
|
|
1005
|
+
iconColor="#8E8E93"
|
|
1006
|
+
onPress={() => void exportData({ encrypt: false })}
|
|
1007
|
+
showChevron={false}
|
|
1008
|
+
/>
|
|
1009
|
+
)}
|
|
998
1010
|
<ListRow
|
|
999
1011
|
label={t('import_wallet_data')}
|
|
1000
1012
|
icon="download-outline"
|