@bsv/expo-wallet-toolbox 0.15.2 → 0.16.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 +158 -0
- package/core/backup/appData.ts +5 -1
- package/core/backup/codec.ts +9 -3
- package/core/backup/contactsBackup.ts +145 -0
- package/core/backup/push.ts +14 -0
- package/core/backup/restoreOnImport.ts +15 -0
- package/core/contacts/contactsStore.ts +47 -3
- package/core/context/LocalStorageProvider.tsx +3 -1
- package/core/context/WalletContext.tsx +5 -2
- package/core/context/startupPrewarm.ts +54 -0
- package/core/hooks/useConfirmationSound.ts +7 -0
- package/core/identity/handleRegistry/client.ts +2 -1
- package/core/identity/handleRegistry/profileKeys.ts +16 -0
- package/core/identity/handleRegistry/resolver.ts +2 -1
- package/core/identity/handleRegistry/rules.ts +7 -3
- package/core/index.ts +2 -1
- package/core/localpay/build.ts +4 -3
- package/core/localpay/session.ts +6 -0
- package/core/localpay/transport/select.ts +64 -3
- package/core/localpay/verify.ts +2 -1
- package/core/net/trimTrailingSlashes.ts +13 -0
- package/core/parsePeerPayURI.ts +25 -2
- package/core/pay/creditInbox.ts +31 -1
- package/core/pay/rails/address.ts +3 -2
- package/core/pay/rails/handle.ts +8 -2
- package/core/pay/rails/index.ts +6 -4
- package/core/pos/protocol.ts +172 -0
- package/core/profiles/removalProblems.ts +41 -0
- package/core/push/registration.ts +2 -1
- package/core/services/revokeConnection.ts +98 -0
- package/core/storage/schema/createTables.ts +24 -0
- package/core/toolboxConfig.ts +22 -4
- package/package.json +1 -1
- package/ui/components/pay/MessageBoxConfig.tsx +2 -1
- package/ui/components/pay/NearbyFlow.tsx +410 -7
- package/ui/exportTransactions.ts +26 -13
- package/ui/index.ts +2 -2
- package/ui/screens/ConnectionsScreen.tsx +8 -63
- package/ui/screens/ProfileScreen.tsx +2 -40
- package/ui/screens/WalletConfigScreen.tsx +57 -51
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,163 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.16.0
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **The backup log carries contacts.** Each push's `appData` now includes the
|
|
8
|
+
contacts table (`core/backup/contactsBackup.ts`): every contact by identity
|
|
9
|
+
key, removed ones too, with its label, star, cached handle and avatar, and
|
|
10
|
+
its dates; never the device-local ids. A restore writes them for the
|
|
11
|
+
restoring wallet's own user, and never rolls a newer edit back; restoring
|
|
12
|
+
from more than one device keeps everyone, each as last changed. An older
|
|
13
|
+
reader ignores the new field. Like the rest of `appData`, the snapshot only
|
|
14
|
+
travels on a push that carries an entity change, so a contact edit with no
|
|
15
|
+
payment after it reaches the log with the next payment.
|
|
16
|
+
- **Point-of-sale payment requests.** `core/pos/protocol.ts` is the wire
|
|
17
|
+
standard for a merchant's nearby payment: a signed `bsvpos1:` code that
|
|
18
|
+
either enrolls a cashier (`Invite`) or asks for one payment
|
|
19
|
+
(`MerchantRequest`: merchant, cashier, invoice, chain, expiry, the pairing
|
|
20
|
+
`session`, and optionally a `subtotal` and `tip` that must add up to the
|
|
21
|
+
session's amount). `sign`/`verify` use the `[2, 'bsv pos authorization']`
|
|
22
|
+
protocol, `encodePos`/`decodePos` do the framing and every field check, and
|
|
23
|
+
`decodePaymentRequest` turns a `bsvpos1:` code or a plain pairing code into
|
|
24
|
+
a `Session`. A merchant code fills the new `Session.merchantName`,
|
|
25
|
+
`merchantChain`, `merchantExpires`, `merchantSubtotal` and `merchantTip`
|
|
26
|
+
(verified display data, never part of the base pairing QR). `NearbyFlow`'s
|
|
27
|
+
payer scanner accepts these codes, names the merchant on the confirm step,
|
|
28
|
+
shows "sale + tip" when there is a tip, and refuses a request that has
|
|
29
|
+
expired or is for another network than the wallet's. Apps import it from
|
|
30
|
+
`core/pos/protocol` (not re-exported from `core/index.ts`).
|
|
31
|
+
- **`NearbyFlow` can be drawn by the host.** Three optional props, all
|
|
32
|
+
unset by default so the built-in screens are unchanged:
|
|
33
|
+
- `embedded` (payee with `initialRequest`): render inline inside a host
|
|
34
|
+
screen. While the request is live only the pairing code and its status
|
|
35
|
+
show, sized `qrSize`; a failure or an already-paid outcome opens full
|
|
36
|
+
screen in a modal, and its Cancel calls `onExit`. `onBusy` reports when a
|
|
37
|
+
payment is in hand, so the host does not remount or unmount the flow.
|
|
38
|
+
- `renderPayer` (payer): `confirm`, `sending`, `showCode` and `done`
|
|
39
|
+
renderers, each optional, handed the values and actions of that step
|
|
40
|
+
(`NearbyConfirm`, `NearbySending`, `NearbyShowCode`, `NearbyDone`, now
|
|
41
|
+
exported from `ui/index.ts`). The logic stays in the flow; a step without
|
|
42
|
+
a renderer keeps its built-in screen.
|
|
43
|
+
- `renderReceived` (payee): draw the "payment received" moment yourself
|
|
44
|
+
(`NearbyReceived`: amount, `amountText` for tokens, `broadcast`,
|
|
45
|
+
`verification`, `payerName`, `dismiss`). It replaces the built-in
|
|
46
|
+
overlay, so present it full screen and play your own sound.
|
|
47
|
+
- **`revokeConnection` is exported.** Signing a paired site out (stop serving
|
|
48
|
+
it at once, then tell it over the relay with a best-effort
|
|
49
|
+
`session_revoke`) moved out of `ConnectionsScreen` into
|
|
50
|
+
`core/services/revokeConnection.ts`, exported from `core/index.ts`, so an
|
|
51
|
+
app's own sign-ins screen revokes the same way. It takes the connection,
|
|
52
|
+
the permissions manager, `{ liveTopic, disconnect }` and optional `deps`
|
|
53
|
+
for tests; `ConnectionsScreen` behaves as before.
|
|
54
|
+
- **Contacts can be starred and removed.** `ContactRow` has `favourite` and
|
|
55
|
+
`removedAt`, and `ContactsStore` has `setFavourite`, `removeContact` and
|
|
56
|
+
`restoreContact`. A removed contact is hidden from `listContacts` and
|
|
57
|
+
`searchContacts` but kept, so adding the person again (or
|
|
58
|
+
`restoreContact`) brings them back; `getContact` still returns it, with
|
|
59
|
+
`removedAt` set. `deleteContact` still deletes the row.
|
|
60
|
+
- **The `contacts` table gains `favourite` and `removedAt`.**
|
|
61
|
+
`createTables` adds both through `ensureContactsColumns`: additive, with
|
|
62
|
+
defaults that mean "as before" (`favourite INTEGER NOT NULL DEFAULT 0`,
|
|
63
|
+
`removedAt TEXT`), so an existing database upgrades on the next open and an
|
|
64
|
+
app that never sets them sees its address book unchanged.
|
|
65
|
+
- **Start-up reads can begin before the app renders.**
|
|
66
|
+
`prewarmStartup()` in `core/context/startupPrewarm.ts` starts the secrets
|
|
67
|
+
migration and the profile and stored-config reads from the app's entry file
|
|
68
|
+
(once the crypto seams are installed). `LocalStorageProvider` and
|
|
69
|
+
`WalletContextProvider` take the reads in flight instead of starting them
|
|
70
|
+
in effects after the first screen has committed. An app that does not call
|
|
71
|
+
it behaves as before, and each prewarmed read is used once; a later run
|
|
72
|
+
(after logout) does its own.
|
|
73
|
+
- **A host-configurable minimum handle length.** `configureToolbox({
|
|
74
|
+
handleMinLength: 1 | 2 | 3 })` (default 3) sets the shortest handle
|
|
75
|
+
`isValidHandleFormat` accepts; `getHandleMinLength()` reads it. The rest of
|
|
76
|
+
the format is unchanged (a-z 0-9 . _ -, at most 32, starting and ending
|
|
77
|
+
with a letter or digit). A host that lowers it must use a registry that
|
|
78
|
+
accepts the shorter handles.
|
|
79
|
+
- **Payment links carry a note.** `peerpay:` links may carry a `note`
|
|
80
|
+
extension (BRC-125's extension rule, so other wallets ignore it).
|
|
81
|
+
`parsePeerPayURI`, `validatePeerPayURI`, `classifyScan` and the `handle`
|
|
82
|
+
pay target return it as `note`, cleaned by the new `cleanPeerPayNote`
|
|
83
|
+
(single line, control characters stripped, at most `PEERPAY_NOTE_MAX` = 120
|
|
84
|
+
characters), and `peerPayLinkFor` takes a trailing `note` argument to write
|
|
85
|
+
one.
|
|
86
|
+
- **A handle payment's note reaches the receiver.** The MessageBox client
|
|
87
|
+
rebuilds a payment from its token fields alone, which dropped the `note`
|
|
88
|
+
the sending side adds. `creditInbox` now puts the sender's note back on each
|
|
89
|
+
parsed payment (`withSenderNotes`) from the raw message.
|
|
90
|
+
- **A host sounds switch.** `sounds.setEnabled(false)` in
|
|
91
|
+
`core/hooks/useConfirmationSound.ts` silences every tone until it is turned
|
|
92
|
+
back on (on by default).
|
|
93
|
+
- **Export a chosen set of transactions.** `exportTransactionsAsCsv` takes an
|
|
94
|
+
optional `select(action)` filter (a period, a direction) and an optional
|
|
95
|
+
`fileName`, and the paging helper behind it is exported as
|
|
96
|
+
`listAllActions(wallet, adminOriginator)`. The existing three-argument call
|
|
97
|
+
is unchanged.
|
|
98
|
+
- **Shared helpers for host screens.** `core/profiles/removalProblems.ts`
|
|
99
|
+
(`removalProblemKeys`) maps a refused or failed profile removal to the
|
|
100
|
+
`profile_remove_*` i18n keys, so every app's Profile screen explains it the
|
|
101
|
+
same way; `core/identity/handleRegistry/profileKeys.ts` exports
|
|
102
|
+
`HANDLE_KV_KEY` and `DISPLAY_NAME_KV_KEY`, the storage keys of a wallet's
|
|
103
|
+
own profile, so a host that registers a handle itself reads and writes the
|
|
104
|
+
same entries as `ProfileScreen`; `core/net/trimTrailingSlashes.ts` is a
|
|
105
|
+
linear-time replacement for `s.replace(/\/+$/, '')`.
|
|
106
|
+
- **`WalletConfigScreen` takes `hideLogout`.** An app that forgets wallets its
|
|
107
|
+
own way and shows the screen only as developer tools can leave the Log Out
|
|
108
|
+
row out. Default false.
|
|
109
|
+
|
|
110
|
+
### Changed
|
|
111
|
+
|
|
112
|
+
- **iOS nearby payments step down AWDL, then BLE, then the QR code.** When
|
|
113
|
+
the AWDL link never came up, the payer now tries Bluetooth (if the payee's
|
|
114
|
+
code offered it and this device can) before showing the payment as a code.
|
|
115
|
+
Only a failure that proves not one byte left the device qualifies
|
|
116
|
+
(`failedBeforeConnect`, matching the native "no route to peer" text), so a
|
|
117
|
+
lost ack or a timeout after the link was up still goes straight to the QR
|
|
118
|
+
fountain: a second radio could deliver the frame twice into a payee race
|
|
119
|
+
that has already settled. `fallbackRadio(session, failed)` and
|
|
120
|
+
`failedBeforeConnect(error)` are exported from `core/index.ts` next to
|
|
121
|
+
`selectTransport`.
|
|
122
|
+
- **The payer skips AWDL when the payee was off Wi-Fi.** A payee that made
|
|
123
|
+
its code with a network probe that answered and found no Wi-Fi advertises
|
|
124
|
+
AWDL anyway (turning Wi-Fi off in Control Center leaves the radio up), but
|
|
125
|
+
AWDL between phones off a network fails in practice and cost the whole
|
|
126
|
+
connect timeout. `selectTransport` now passes over it in that case
|
|
127
|
+
(`peerKnownOffWifi` in `core/localpay/transport/select.ts`). A code with no
|
|
128
|
+
probe answer, or an older one with no hint bits, is not "off" and keeps the
|
|
129
|
+
AWDL rung.
|
|
130
|
+
- **Contacts come back from the address book without removed ones.**
|
|
131
|
+
`listContacts` and `searchContacts` leave out contacts with `removedAt` set
|
|
132
|
+
(see Added). `ContactRow.favourite` is a required boolean, so code that
|
|
133
|
+
builds a `ContactRow` or implements `ContactsStore` itself must supply it
|
|
134
|
+
and the three new methods.
|
|
135
|
+
- **Handle format check is length-driven.** `isValidHandleFormat` now tests
|
|
136
|
+
the length against `getHandleMinLength()` and the character shape
|
|
137
|
+
separately; with the default configuration it accepts exactly the same
|
|
138
|
+
3-32 character handles as before.
|
|
139
|
+
- **Trailing-slash trimming on URLs no longer backtracks.** Every
|
|
140
|
+
`replace(/\/+$/, '')` on a URL that can arrive from a link, QR code or other
|
|
141
|
+
app (backup, push, MessageBox, overlay, registry, `peerpay:` and
|
|
142
|
+
token-overlay comparison) now uses `trimTrailingSlashes`, removing a
|
|
143
|
+
quadratic-time pattern (CodeQL `js/polynomial-redos`). Results are
|
|
144
|
+
identical.
|
|
145
|
+
- **`ProfileScreen` and `ConnectionsScreen` use the shared helpers** above
|
|
146
|
+
instead of local copies; what they show is unchanged.
|
|
147
|
+
|
|
148
|
+
### Fixed
|
|
149
|
+
|
|
150
|
+
- **Short payment notes no longer fail the send.** A wallet action's
|
|
151
|
+
description must be at least 5 bytes and the validator does not trim, so a
|
|
152
|
+
note like "ok" made `createAction` fail on the nearby (BSV and token) and
|
|
153
|
+
address rails. The description is now space-padded to 5
|
|
154
|
+
(`core/localpay/build.ts`, `core/pay/rails/address.ts`). The padding is
|
|
155
|
+
also needed where the note goes through `@bsv/mandala` (its send and
|
|
156
|
+
receive notes); that is in the mandala package, not here. Until mandala
|
|
157
|
+
fixes it, apps must carry a `patch-package` patch for `@bsv/mandala` 0.4.1
|
|
158
|
+
that pads the description the same way.
|
|
159
|
+
|
|
160
|
+
|
|
3
161
|
## 0.15.2
|
|
4
162
|
|
|
5
163
|
### Fixed
|
package/core/backup/appData.ts
CHANGED
|
@@ -48,6 +48,7 @@ import { OUTBOX_KEY } from '../peerpay/outbox'
|
|
|
48
48
|
import { PENDING_KEY } from '../localpay/pending'
|
|
49
49
|
import { getIssuedDates, setIssuedDates } from '../pay/receiveHistory'
|
|
50
50
|
import type { AppDataSnapshot } from './codec'
|
|
51
|
+
import { mergeContacts } from './contactsBackup'
|
|
51
52
|
|
|
52
53
|
export interface KVStorage {
|
|
53
54
|
getKeyValue (k: string): Promise<string | undefined>
|
|
@@ -63,6 +64,7 @@ export function isEmptyAppData (appData: AppDataSnapshot | undefined): boolean {
|
|
|
63
64
|
appData == null ||
|
|
64
65
|
(appData.localpayPending === undefined &&
|
|
65
66
|
appData.peerpayOutbox === undefined &&
|
|
67
|
+
appData.contacts === undefined &&
|
|
66
68
|
(appData.receiveIssuedDates?.length ?? 0) === 0)
|
|
67
69
|
)
|
|
68
70
|
}
|
|
@@ -152,6 +154,8 @@ export function mergeAppData (a: AppDataSnapshot | undefined, b: AppDataSnapshot
|
|
|
152
154
|
receiveIssuedDates:
|
|
153
155
|
a?.receiveIssuedDates === undefined && b?.receiveIssuedDates === undefined
|
|
154
156
|
? undefined
|
|
155
|
-
: [...new Set([...(a?.receiveIssuedDates ?? []), ...(b?.receiveIssuedDates ?? [])])].sort()
|
|
157
|
+
: [...new Set([...(a?.receiveIssuedDates ?? []), ...(b?.receiveIssuedDates ?? [])])].sort(),
|
|
158
|
+
// everyone either device knew, each as they were last changed (contactsBackup.ts)
|
|
159
|
+
contacts: mergeContacts(a?.contacts, b?.contacts)
|
|
156
160
|
}
|
|
157
161
|
}
|
package/core/backup/codec.ts
CHANGED
|
@@ -113,7 +113,7 @@ export function estimateEncodedBytes (chunk: SyncChunk): number {
|
|
|
113
113
|
*/
|
|
114
114
|
export function estimateAppDataBytes (appData: AppDataSnapshot | undefined): number {
|
|
115
115
|
if (appData == null) return 0
|
|
116
|
-
let bytes = (appData.localpayPending?.length ?? 0) + (appData.peerpayOutbox?.length ?? 0)
|
|
116
|
+
let bytes = (appData.localpayPending?.length ?? 0) + (appData.peerpayOutbox?.length ?? 0) + (appData.contacts?.length ?? 0)
|
|
117
117
|
for (const d of appData.receiveIssuedDates ?? []) bytes += d.length
|
|
118
118
|
return bytes
|
|
119
119
|
}
|
|
@@ -173,6 +173,8 @@ export interface AppDataSnapshot {
|
|
|
173
173
|
peerpayOutbox?: string
|
|
174
174
|
/** Every YYYY-MM-DD a conventional-receive address has been issued for, deduplicated. */
|
|
175
175
|
receiveIssuedDates?: string[]
|
|
176
|
+
/** The contacts table, as JSON (backup/contactsBackup.ts). */
|
|
177
|
+
contacts?: string
|
|
176
178
|
}
|
|
177
179
|
|
|
178
180
|
/**
|
|
@@ -275,7 +277,7 @@ export async function decodeEntry (
|
|
|
275
277
|
* restore, not quietly disappear (same failure posture as a malformed seal, above). */
|
|
276
278
|
function decodeAppData (raw: unknown): AppDataSnapshot | undefined {
|
|
277
279
|
if (raw == null) return undefined
|
|
278
|
-
const a = raw as { localpayPending?: unknown, peerpayOutbox?: unknown, receiveIssuedDates?: unknown }
|
|
280
|
+
const a = raw as { localpayPending?: unknown, peerpayOutbox?: unknown, receiveIssuedDates?: unknown, contacts?: unknown }
|
|
279
281
|
if (a.localpayPending !== undefined && typeof a.localpayPending !== 'string') {
|
|
280
282
|
throw new Error('backup appData.localpayPending is malformed')
|
|
281
283
|
}
|
|
@@ -288,10 +290,14 @@ function decodeAppData (raw: unknown): AppDataSnapshot | undefined {
|
|
|
288
290
|
) {
|
|
289
291
|
throw new Error('backup appData.receiveIssuedDates is malformed')
|
|
290
292
|
}
|
|
293
|
+
if (a.contacts !== undefined && typeof a.contacts !== 'string') {
|
|
294
|
+
throw new Error('backup appData.contacts is malformed')
|
|
295
|
+
}
|
|
291
296
|
return {
|
|
292
297
|
localpayPending: a.localpayPending as string | undefined,
|
|
293
298
|
peerpayOutbox: a.peerpayOutbox as string | undefined,
|
|
294
|
-
receiveIssuedDates: a.receiveIssuedDates as string[] | undefined
|
|
299
|
+
receiveIssuedDates: a.receiveIssuedDates as string[] | undefined,
|
|
300
|
+
...(a.contacts !== undefined ? { contacts: a.contacts as string } : {})
|
|
295
301
|
}
|
|
296
302
|
}
|
|
297
303
|
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The contacts table, carried in the backup log's appData envelope (see appData.ts), so a
|
|
3
|
+
* restore brings back the people a wallet knows, not just its money and history.
|
|
4
|
+
*
|
|
5
|
+
* Contacts are people by identity key (core/contacts/contactsStore.ts). Every row goes,
|
|
6
|
+
* removed ones too — a removal is itself something to restore — with the user's own label,
|
|
7
|
+
* the star, and the cached handle and avatar (refreshed in the background anyway). Never the
|
|
8
|
+
* device-local `contactId` or `userId`: on restore the rows are written for the restoring
|
|
9
|
+
* wallet's own local user.
|
|
10
|
+
*
|
|
11
|
+
* Same limit as the rest of appData (see its module docs): the snapshot only travels on a
|
|
12
|
+
* push that carries a real entity change, so an edit made with no payment after it reaches
|
|
13
|
+
* the log with the next payment.
|
|
14
|
+
*/
|
|
15
|
+
import type { ContactsDb, ContactSource } from '../contacts/contactsStore'
|
|
16
|
+
|
|
17
|
+
/** One contact as the backup carries it. */
|
|
18
|
+
export interface BackedUpContact {
|
|
19
|
+
identityKey: string
|
|
20
|
+
name: string
|
|
21
|
+
cachedHandle?: string
|
|
22
|
+
cachedAvatarUrl?: string
|
|
23
|
+
cachedCertifier?: string
|
|
24
|
+
source: ContactSource
|
|
25
|
+
favourite: boolean
|
|
26
|
+
removedAt?: string
|
|
27
|
+
createdAt: string
|
|
28
|
+
updatedAt: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const SOURCES: ContactSource[] = ['manual', 'qr', 'pay', 'search']
|
|
32
|
+
|
|
33
|
+
interface Row {
|
|
34
|
+
identityKey: string
|
|
35
|
+
name: string
|
|
36
|
+
cachedHandle: string | null
|
|
37
|
+
cachedAvatarUrl: string | null
|
|
38
|
+
cachedCertifier: string | null
|
|
39
|
+
source: string
|
|
40
|
+
created_at: string
|
|
41
|
+
updated_at: string
|
|
42
|
+
favourite: number | null
|
|
43
|
+
removedAt: string | null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Every contact of a local user, removed ones included, as JSON; undefined when there are none. */
|
|
47
|
+
export async function captureContacts (db: ContactsDb, userId: number): Promise<string | undefined> {
|
|
48
|
+
const rows = (await db.getAllAsync(
|
|
49
|
+
'SELECT identityKey, name, cachedHandle, cachedAvatarUrl, cachedCertifier, source, created_at, updated_at, favourite, removedAt FROM contacts WHERE userId = ?',
|
|
50
|
+
[userId]
|
|
51
|
+
)) as Row[]
|
|
52
|
+
if (rows.length === 0) return undefined
|
|
53
|
+
const contacts: BackedUpContact[] = rows.map(r => ({
|
|
54
|
+
identityKey: r.identityKey,
|
|
55
|
+
name: r.name,
|
|
56
|
+
...(r.cachedHandle ? { cachedHandle: r.cachedHandle } : {}),
|
|
57
|
+
...(r.cachedAvatarUrl ? { cachedAvatarUrl: r.cachedAvatarUrl } : {}),
|
|
58
|
+
...(r.cachedCertifier ? { cachedCertifier: r.cachedCertifier } : {}),
|
|
59
|
+
source: (SOURCES as string[]).includes(r.source) ? (r.source as ContactSource) : 'manual',
|
|
60
|
+
favourite: !!r.favourite,
|
|
61
|
+
...(r.removedAt ? { removedAt: r.removedAt } : {}),
|
|
62
|
+
createdAt: r.created_at,
|
|
63
|
+
updatedAt: r.updated_at
|
|
64
|
+
}))
|
|
65
|
+
return JSON.stringify(contacts)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The contacts in a snapshot, never throwing: anything malformed is left out. */
|
|
69
|
+
export function parseContacts (raw: string | undefined): BackedUpContact[] {
|
|
70
|
+
if (raw === undefined) return []
|
|
71
|
+
let parsed: unknown
|
|
72
|
+
try {
|
|
73
|
+
parsed = JSON.parse(raw)
|
|
74
|
+
} catch {
|
|
75
|
+
return []
|
|
76
|
+
}
|
|
77
|
+
if (!Array.isArray(parsed)) return []
|
|
78
|
+
return parsed.filter(
|
|
79
|
+
(c): c is BackedUpContact =>
|
|
80
|
+
c != null &&
|
|
81
|
+
typeof c === 'object' &&
|
|
82
|
+
typeof (c as BackedUpContact).identityKey === 'string' &&
|
|
83
|
+
(c as BackedUpContact).identityKey !== '' &&
|
|
84
|
+
typeof (c as BackedUpContact).name === 'string' &&
|
|
85
|
+
typeof (c as BackedUpContact).updatedAt === 'string'
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Two devices' contacts as one: everyone from both, and where both know someone, whichever
|
|
91
|
+
* changed them last (a rename, a star or a removal made on one phone wins over the older
|
|
92
|
+
* state on the other).
|
|
93
|
+
*/
|
|
94
|
+
export function mergeContacts (a: string | undefined, b: string | undefined): string | undefined {
|
|
95
|
+
if (a === undefined) return b
|
|
96
|
+
if (b === undefined) return a
|
|
97
|
+
const byKey = new Map<string, BackedUpContact>()
|
|
98
|
+
for (const c of [...parseContacts(a), ...parseContacts(b)]) {
|
|
99
|
+
const key = c.identityKey.toLowerCase()
|
|
100
|
+
const had = byKey.get(key)
|
|
101
|
+
if (!had || Date.parse(c.updatedAt) > Date.parse(had.updatedAt)) byKey.set(key, c)
|
|
102
|
+
}
|
|
103
|
+
return JSON.stringify([...byKey.values()])
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Write a snapshot's contacts for a local user. Someone not here yet is added as they were
|
|
108
|
+
* (label, star, removal, dates); someone already here is updated only when the backup's copy
|
|
109
|
+
* is newer, so re-running an interrupted restore never rolls an edit back.
|
|
110
|
+
*/
|
|
111
|
+
export async function applyContacts (db: ContactsDb, userId: number, raw: string | undefined): Promise<number> {
|
|
112
|
+
let written = 0
|
|
113
|
+
for (const c of parseContacts(raw)) {
|
|
114
|
+
const had = (await db.getFirstAsync('SELECT updated_at FROM contacts WHERE userId = ? AND identityKey = ?', [userId, c.identityKey])) as
|
|
115
|
+
| { updated_at: string }
|
|
116
|
+
| null
|
|
117
|
+
| undefined
|
|
118
|
+
const values = [
|
|
119
|
+
c.name,
|
|
120
|
+
c.cachedHandle ?? null,
|
|
121
|
+
c.cachedAvatarUrl ?? null,
|
|
122
|
+
c.cachedCertifier ?? null,
|
|
123
|
+
SOURCES.includes(c.source) ? c.source : 'manual',
|
|
124
|
+
c.favourite ? 1 : 0,
|
|
125
|
+
c.removedAt ?? null,
|
|
126
|
+
c.updatedAt
|
|
127
|
+
]
|
|
128
|
+
if (!had) {
|
|
129
|
+
await db.runAsync(
|
|
130
|
+
`INSERT INTO contacts (name, cachedHandle, cachedAvatarUrl, cachedCertifier, source, favourite, removedAt, updated_at, created_at, userId, identityKey)
|
|
131
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
132
|
+
[...values, c.createdAt || c.updatedAt, userId, c.identityKey]
|
|
133
|
+
)
|
|
134
|
+
written++
|
|
135
|
+
} else if (Date.parse(c.updatedAt) > Date.parse(had.updated_at)) {
|
|
136
|
+
await db.runAsync(
|
|
137
|
+
`UPDATE contacts SET name = ?, cachedHandle = ?, cachedAvatarUrl = ?, cachedCertifier = ?, source = ?, favourite = ?, removedAt = ?, updated_at = ?
|
|
138
|
+
WHERE userId = ? AND identityKey = ?`,
|
|
139
|
+
[...values, userId, c.identityKey]
|
|
140
|
+
)
|
|
141
|
+
written++
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return written
|
|
145
|
+
}
|
package/core/backup/push.ts
CHANGED
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
|
|
19
19
|
import { captureAppDataSnapshot, isEmptyAppData } from './appData'
|
|
20
|
+
import { captureContacts } from './contactsBackup'
|
|
21
|
+
import type { ContactsDb } from '../contacts/contactsStore'
|
|
20
22
|
import { BackupClient, BackupHttpError, ERR_SEQ_CONFLICT } from './client'
|
|
21
23
|
import { encodeChunk, estimateAppDataBytes, estimateEncodedBytes, isEmptyChunk, type BackupSeal } from './codec'
|
|
22
24
|
import { GENERATION_CHUNK_THRESHOLD, MAX_ITEMS, MAX_ROUGH_SIZE, type BackupChain } from './constants'
|
|
@@ -180,6 +182,18 @@ export async function pushOnce (deps: PushDeps): Promise<PushResult> {
|
|
|
180
182
|
// when there is nothing app-owned to add, so a chunk with an empty queue serialises
|
|
181
183
|
// byte-for-byte as the pre-appData envelope (see encodeChunk's own docs).
|
|
182
184
|
const appData = await captureAppDataSnapshot(deps.storage)
|
|
185
|
+
// the contacts too (contactsBackup.ts): a read that fails leaves them out of this push
|
|
186
|
+
// rather than failing it
|
|
187
|
+
try {
|
|
188
|
+
const db = deps.storage.sqliteDb
|
|
189
|
+
if (db) {
|
|
190
|
+
const { user } = await deps.storage.findOrInsertUser(deps.identityKey)
|
|
191
|
+
const contacts = await captureContacts(db as unknown as ContactsDb, user.userId)
|
|
192
|
+
if (contacts !== undefined) appData.contacts = contacts
|
|
193
|
+
}
|
|
194
|
+
} catch {
|
|
195
|
+
// contacts wait for the next push
|
|
196
|
+
}
|
|
183
197
|
const appDataToSend = isEmptyAppData(appData) ? undefined : appData
|
|
184
198
|
|
|
185
199
|
// Bail BEFORE the expensive part when the chunk cannot possibly be accepted.
|
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
*/
|
|
36
36
|
import type { StorageExpoSQLite } from '../storage/StorageExpoSQLite'
|
|
37
37
|
import { applyAppData, mergeAppData } from './appData'
|
|
38
|
+
import { applyContacts } from './contactsBackup'
|
|
39
|
+
import type { ContactsDb } from '../contacts/contactsStore'
|
|
38
40
|
import { BackupClient } from './client'
|
|
39
41
|
import type { AppDataSnapshot } from './codec'
|
|
40
42
|
import type { BackupChain } from './constants'
|
|
@@ -167,6 +169,19 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
|
|
|
167
169
|
// (see appData.ts's applyAppData docs).
|
|
168
170
|
if (appData !== undefined) {
|
|
169
171
|
await applyAppData(deps.storage, appData)
|
|
172
|
+
// the contacts, for this wallet's own local user (contactsBackup.ts); a failure here
|
|
173
|
+
// costs the contacts, never the restore
|
|
174
|
+
if (appData.contacts !== undefined) {
|
|
175
|
+
try {
|
|
176
|
+
const db = deps.storage.sqliteDb
|
|
177
|
+
if (db) {
|
|
178
|
+
const { user } = await deps.storage.findOrInsertUser(deps.identityKey)
|
|
179
|
+
await applyContacts(db as unknown as ContactsDb, user.userId, appData.contacts)
|
|
180
|
+
}
|
|
181
|
+
} catch (error) {
|
|
182
|
+
console.warn('[backup] contacts could not be restored', (error as Error)?.message)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
170
185
|
}
|
|
171
186
|
|
|
172
187
|
if (deps.validateRestoredCoins) {
|
|
@@ -41,6 +41,11 @@ export interface ContactRow {
|
|
|
41
41
|
source: ContactSource
|
|
42
42
|
createdAt: string
|
|
43
43
|
updatedAt: string
|
|
44
|
+
/** Starred by the user. */
|
|
45
|
+
favourite: boolean
|
|
46
|
+
/** When the user took them out of the address book; set means hidden from
|
|
47
|
+
* lists and searches but kept, so it can be undone. */
|
|
48
|
+
removedAt?: string
|
|
44
49
|
}
|
|
45
50
|
|
|
46
51
|
interface ContactDbRow {
|
|
@@ -54,6 +59,9 @@ interface ContactDbRow {
|
|
|
54
59
|
source: string
|
|
55
60
|
created_at: string
|
|
56
61
|
updated_at: string
|
|
62
|
+
// added by ensureContactsColumns; absent on a table that predates them
|
|
63
|
+
favourite?: number | null
|
|
64
|
+
removedAt?: string | null
|
|
57
65
|
}
|
|
58
66
|
|
|
59
67
|
function toContact(row: ContactDbRow): ContactRow {
|
|
@@ -67,15 +75,19 @@ function toContact(row: ContactDbRow): ContactRow {
|
|
|
67
75
|
cachedCertifier: row.cachedCertifier ?? undefined,
|
|
68
76
|
source: row.source as ContactSource,
|
|
69
77
|
createdAt: row.created_at,
|
|
70
|
-
updatedAt: row.updated_at
|
|
78
|
+
updatedAt: row.updated_at,
|
|
79
|
+
favourite: !!row.favourite,
|
|
80
|
+
removedAt: row.removedAt ?? undefined
|
|
71
81
|
}
|
|
72
82
|
}
|
|
73
83
|
|
|
74
84
|
export interface ContactsStore {
|
|
85
|
+
/** The address book: everyone not removed. */
|
|
75
86
|
listContacts(userId: number): Promise<ContactRow[]>
|
|
76
87
|
/** Case-insensitive substring match on `name` and `cachedHandle`. Forgiving,
|
|
77
88
|
* not scored — "fuzzy" in the design sense, not a ranked fuzzy algorithm. */
|
|
78
89
|
searchContacts(userId: number, query: string): Promise<ContactRow[]>
|
|
90
|
+
/** Including a removed one (check `removedAt`): adding them again restores them. */
|
|
79
91
|
getContact(userId: number, identityKey: string): Promise<ContactRow | undefined>
|
|
80
92
|
/** Throws on a duplicate (userId, identityKey) — callers check `getContact` first when they need "already a contact" as a non-throwing fact. */
|
|
81
93
|
createContact(args: {
|
|
@@ -96,12 +108,17 @@ export interface ContactsStore {
|
|
|
96
108
|
cache: { cachedHandle?: string; cachedAvatarUrl?: string; cachedCertifier?: string }
|
|
97
109
|
): Promise<void>
|
|
98
110
|
deleteContact(userId: number, identityKey: string): Promise<void>
|
|
111
|
+
/** Star or unstar. */
|
|
112
|
+
setFavourite(userId: number, identityKey: string, favourite: boolean): Promise<void>
|
|
113
|
+
/** Take out of the address book, keeping the row so `restoreContact` can undo it. */
|
|
114
|
+
removeContact(userId: number, identityKey: string): Promise<void>
|
|
115
|
+
restoreContact(userId: number, identityKey: string): Promise<void>
|
|
99
116
|
}
|
|
100
117
|
|
|
101
118
|
export function createContactsStore(db: ContactsDb): ContactsStore {
|
|
102
119
|
return {
|
|
103
120
|
async listContacts(userId) {
|
|
104
|
-
const rows = (await db.getAllAsync('SELECT * FROM contacts WHERE userId = ? ORDER BY name COLLATE NOCASE ASC', [
|
|
121
|
+
const rows = (await db.getAllAsync('SELECT * FROM contacts WHERE userId = ? AND removedAt IS NULL ORDER BY name COLLATE NOCASE ASC', [
|
|
105
122
|
userId
|
|
106
123
|
])) as ContactDbRow[]
|
|
107
124
|
return rows.map(toContact)
|
|
@@ -112,7 +129,7 @@ export function createContactsStore(db: ContactsDb): ContactsStore {
|
|
|
112
129
|
if (query.trim() === '') return createContactsStore(db).listContacts(userId)
|
|
113
130
|
const rows = (await db.getAllAsync(
|
|
114
131
|
`SELECT * FROM contacts
|
|
115
|
-
WHERE userId = ?
|
|
132
|
+
WHERE userId = ? AND removedAt IS NULL
|
|
116
133
|
AND (lower(name) LIKE ? OR lower(coalesce(cachedHandle, '')) LIKE ?)
|
|
117
134
|
ORDER BY name COLLATE NOCASE ASC`,
|
|
118
135
|
[userId, needle, needle]
|
|
@@ -178,6 +195,33 @@ export function createContactsStore(db: ContactsDb): ContactsStore {
|
|
|
178
195
|
|
|
179
196
|
async deleteContact(userId, identityKey) {
|
|
180
197
|
await db.runAsync('DELETE FROM contacts WHERE userId = ? AND identityKey = ?', [userId, identityKey])
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
async setFavourite(userId, identityKey, favourite) {
|
|
201
|
+
await db.runAsync('UPDATE contacts SET favourite = ?, updated_at = ? WHERE userId = ? AND identityKey = ?', [
|
|
202
|
+
favourite ? 1 : 0,
|
|
203
|
+
new Date().toISOString(),
|
|
204
|
+
userId,
|
|
205
|
+
identityKey
|
|
206
|
+
])
|
|
207
|
+
},
|
|
208
|
+
|
|
209
|
+
async removeContact(userId, identityKey) {
|
|
210
|
+
const now = new Date().toISOString()
|
|
211
|
+
await db.runAsync('UPDATE contacts SET removedAt = ?, updated_at = ? WHERE userId = ? AND identityKey = ?', [
|
|
212
|
+
now,
|
|
213
|
+
now,
|
|
214
|
+
userId,
|
|
215
|
+
identityKey
|
|
216
|
+
])
|
|
217
|
+
},
|
|
218
|
+
|
|
219
|
+
async restoreContact(userId, identityKey) {
|
|
220
|
+
await db.runAsync('UPDATE contacts SET removedAt = NULL, updated_at = ? WHERE userId = ? AND identityKey = ?', [
|
|
221
|
+
new Date().toISOString(),
|
|
222
|
+
userId,
|
|
223
|
+
identityKey
|
|
224
|
+
])
|
|
181
225
|
}
|
|
182
226
|
}
|
|
183
227
|
}
|
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
type MigrationResult,
|
|
19
19
|
type UnlockState
|
|
20
20
|
} from '../services/secrets'
|
|
21
|
+
import { takeStartupSecrets } from './startupPrewarm'
|
|
21
22
|
|
|
22
23
|
// The identity is shared storage, so overlapping provider mounts must share the
|
|
23
24
|
// guard too. Hold it through both the existence check and the completed write.
|
|
@@ -112,7 +113,8 @@ export default function LocalStorageProvider({ children }: { children: React.Rea
|
|
|
112
113
|
;(async () => {
|
|
113
114
|
let result: MigrationResult
|
|
114
115
|
try {
|
|
115
|
-
|
|
116
|
+
// begun at startup if the app prewarmed (core/context/startupPrewarm)
|
|
117
|
+
result = await (takeStartupSecrets() ?? migrateLegacySecrets())
|
|
116
118
|
} catch (err) {
|
|
117
119
|
console.warn('[LocalStorageProvider] migration threw', (err as Error)?.message)
|
|
118
120
|
result = { outcome: 'failed', stage: 'unknown', retryable: true }
|
|
@@ -206,6 +206,7 @@ import {
|
|
|
206
206
|
combineEmpty,
|
|
207
207
|
type DatabasesEmptyDeps
|
|
208
208
|
} from '../profiles/assertProfileEmpty'
|
|
209
|
+
import { takeStartupConfig } from './startupPrewarm'
|
|
209
210
|
import { purgeProfile, purgeRemovedProfiles, type PurgeProfileIo } from '../profiles/purgeProfile'
|
|
210
211
|
import {
|
|
211
212
|
checkProfileRemoval as runProfileRemovalCheck,
|
|
@@ -1356,13 +1357,15 @@ export const WalletContextProvider: React.FC<WalletContextProps> = ({ children =
|
|
|
1356
1357
|
// The active profile picks the network, keys and database, so it must be in
|
|
1357
1358
|
// memory before anything builds. Per-profile caches that were read at import
|
|
1358
1359
|
// or mount time (before this resolved) are re-read for the profile it names.
|
|
1359
|
-
|
|
1360
|
+
// begun at startup if the app prewarmed (core/context/startupPrewarm)
|
|
1361
|
+
const warm = takeStartupConfig()
|
|
1362
|
+
await (warm ? warm.profiles : loadProfiles())
|
|
1360
1363
|
// A removal that stopped between its tombstone and its purge (a crash, a
|
|
1361
1364
|
// locked store) still has its history on disk: purge it again. Idempotent,
|
|
1362
1365
|
// best effort, and never in the way of startup.
|
|
1363
1366
|
void purgeRemovedProfiles(getProfilesState().profiles, profilePurgeIo).catch(() => {})
|
|
1364
1367
|
await reloadProfileCaches()
|
|
1365
|
-
const storedConfig = await getItem('finalConfig')
|
|
1368
|
+
const storedConfig = warm ? await warm.config : await getItem('finalConfig')
|
|
1366
1369
|
if (storedConfig) {
|
|
1367
1370
|
try {
|
|
1368
1371
|
const config = JSON.parse(storedConfig)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Startup reads that need nothing from React, begun before the app renders.
|
|
3
|
+
*
|
|
4
|
+
* LocalStorageProvider's secrets migration and WalletContext's configuration
|
|
5
|
+
* (the profiles, then the stored config) used to start in effects, after the
|
|
6
|
+
* whole first screen had rendered and committed; the wallet build waits on both.
|
|
7
|
+
* An app calls prewarmStartup() from its entry file, once the crypto seams are
|
|
8
|
+
* installed, and the reads run while the app renders. Each is taken once: the
|
|
9
|
+
* provider that would have started it awaits the one in flight instead. Taken,
|
|
10
|
+
* or never begun (an app that doesn't prewarm), the provider does the work
|
|
11
|
+
* itself, as before; a later run (after logout) always does.
|
|
12
|
+
*/
|
|
13
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
14
|
+
import { loadProfiles } from '../profiles/profileStore'
|
|
15
|
+
import { migrateLegacySecrets, type MigrationResult } from '../services/secrets'
|
|
16
|
+
|
|
17
|
+
export interface StartupConfig {
|
|
18
|
+
/** loadProfiles(), done: the active profile is in memory */
|
|
19
|
+
profiles: Promise<unknown>
|
|
20
|
+
/** the stored 'finalConfig', read once the profiles are */
|
|
21
|
+
config: Promise<string | null>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let secrets: Promise<MigrationResult> | null = null
|
|
25
|
+
let config: StartupConfig | null = null
|
|
26
|
+
|
|
27
|
+
export function prewarmStartup(): void {
|
|
28
|
+
if (!secrets) {
|
|
29
|
+
secrets = migrateLegacySecrets()
|
|
30
|
+
// taken later (or never): an unhandled rejection meanwhile is noise
|
|
31
|
+
secrets.catch(() => {})
|
|
32
|
+
}
|
|
33
|
+
if (!config) {
|
|
34
|
+
const profiles = loadProfiles()
|
|
35
|
+
const stored = profiles.then(() => AsyncStorage.getItem('finalConfig'))
|
|
36
|
+
profiles.catch(() => {})
|
|
37
|
+
stored.catch(() => {})
|
|
38
|
+
config = { profiles, config: stored }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The secrets migration begun at startup, if there's one not yet taken. */
|
|
43
|
+
export function takeStartupSecrets(): Promise<MigrationResult> | null {
|
|
44
|
+
const taken = secrets
|
|
45
|
+
secrets = null
|
|
46
|
+
return taken
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The configuration reads begun at startup, if not yet taken. */
|
|
50
|
+
export function takeStartupConfig(): StartupConfig | null {
|
|
51
|
+
const taken = config
|
|
52
|
+
config = null
|
|
53
|
+
return taken
|
|
54
|
+
}
|
|
@@ -61,6 +61,8 @@ interface AudioModule {
|
|
|
61
61
|
|
|
62
62
|
let audio: AudioModule | null | undefined
|
|
63
63
|
let modeSet = false
|
|
64
|
+
/** The host's own "sounds" preference; on unless it says otherwise. */
|
|
65
|
+
let enabled = true
|
|
64
66
|
const players: Partial<Record<ToneName, Player>> = {}
|
|
65
67
|
|
|
66
68
|
function warn(e: unknown): void {
|
|
@@ -85,6 +87,7 @@ function load(): AudioModule | null {
|
|
|
85
87
|
* user-facing path ever waits on CoreAudio. One reused player per tone.
|
|
86
88
|
*/
|
|
87
89
|
function playTone(name: ToneName): void {
|
|
90
|
+
if (!enabled) return
|
|
88
91
|
const mod = load()
|
|
89
92
|
if (!mod) return
|
|
90
93
|
void (async () => {
|
|
@@ -136,6 +139,10 @@ export const sounds = {
|
|
|
136
139
|
/** Funds moved out of the vault. Pairs with `haptics.success()`. */
|
|
137
140
|
vaultWithdraw: () => playTone('vaultWithdraw'),
|
|
138
141
|
release: releaseAll,
|
|
142
|
+
/** A host's sounds setting: off silences every tone until it's turned on again. */
|
|
143
|
+
setEnabled: (on: boolean) => {
|
|
144
|
+
enabled = on
|
|
145
|
+
},
|
|
139
146
|
} as const
|
|
140
147
|
|
|
141
148
|
export const useConfirmationSound = () => useMemo(() => sounds, [])
|