@bsv/expo-wallet-toolbox 0.15.2 → 0.17.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 +199 -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/restore.ts +26 -4
- package/core/backup/restoreOnImport.ts +28 -4
- package/core/contacts/contactsStore.ts +47 -3
- package/core/context/LocalStorageProvider.tsx +3 -1
- package/core/context/WalletContext.tsx +256 -76
- package/core/context/startupPrewarm.ts +54 -0
- package/core/directpay/dialFailure.ts +56 -0
- package/core/directpay/index.ts +7 -0
- package/core/directpay/payFlow.ts +117 -0
- package/core/directpay/paymentKey.ts +16 -0
- package/core/directpay/settings.ts +253 -0
- package/core/directpay/status.ts +52 -0
- package/core/directpay/types.ts +128 -0
- package/core/hooks/useConfirmationSound.ts +7 -0
- package/core/i18n/translations.tsx +354 -12
- 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 +14 -2
- 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/discovery.ts +17 -8
- package/core/profiles/profileStore.ts +34 -7
- package/core/profiles/removalProblems.ts +41 -0
- package/core/push/registration.ts +2 -1
- package/core/services/callbackToken.ts +7 -0
- package/core/services/revokeConnection.ts +98 -0
- package/core/storage/schema/createTables.ts +24 -0
- package/core/toolboxConfig.ts +85 -5
- 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,204 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.17.0
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **Direct pay core for push payments** (`core/directpay/`, exported from
|
|
8
|
+
`core/index.ts`). This is the device-free half of paying a person live over
|
|
9
|
+
WebRTC, mirroring BSV Desktop:
|
|
10
|
+
- **Settings.** Receiving is on by default. The default relay is
|
|
11
|
+
`wss://webrtpay-relay-us-1.bsvblockchain.tech`, and BSV Association's STUN
|
|
12
|
+
server comes first. Relay, STUN and TURN addresses are validated without
|
|
13
|
+
`URL`. Settings are stored per device under `direct_pay_settings_v1`
|
|
14
|
+
through the host's `KVStorage`.
|
|
15
|
+
- **`payIdentity`.** Outcomes are `paid_live`, `paid_messagebox`,
|
|
16
|
+
`ask_fallback` and `failed`.
|
|
17
|
+
- **"Isn't online" prompt.** This prompt is the only route to the message
|
|
18
|
+
box, and only when nothing was spent: a route that stops first must
|
|
19
|
+
throw `NotSentError`.
|
|
20
|
+
- **`dialFailure`** classifies a dial error.
|
|
21
|
+
- **`liveStatus`** gives the Receive card's status.
|
|
22
|
+
- **`paymentKey`** is the dedupe key shared with the desktop.
|
|
23
|
+
- **Host config.** `configureToolbox` takes an optional `directPay` field,
|
|
24
|
+
read with `getDirectPayConfig()`. It is unset by default, so existing
|
|
25
|
+
hosts see no change.
|
|
26
|
+
- **Translations.** The new strings are in all 12 locales.
|
|
27
|
+
|
|
28
|
+
Nothing is wired into `WalletContext` or a screen yet. The live manager
|
|
29
|
+
and receive/send rails follow in a later release.
|
|
30
|
+
- **`deriveCallbackToken` is exported.** Known-answer vectors pin it. BSV
|
|
31
|
+
Desktop now derives the same Arcade callback token, so a wallet open in both
|
|
32
|
+
apps hears one status stream. No behaviour change.
|
|
33
|
+
|
|
34
|
+
### Fixed
|
|
35
|
+
|
|
36
|
+
- **Backups restore on every network.** A seed imported on mainnet then
|
|
37
|
+
switched to testnet or teratestnet came up empty even when the server held
|
|
38
|
+
a backup for that network. Each network's backup is now restored the first
|
|
39
|
+
time that network's database is built: after an import, on a network
|
|
40
|
+
switch, and for every network a discovered profile has backups on. Profile
|
|
41
|
+
0's other networks are included. Backup format, derivation and keys are
|
|
42
|
+
unchanged.
|
|
43
|
+
|
|
44
|
+
## 0.16.0
|
|
45
|
+
|
|
46
|
+
### Added
|
|
47
|
+
|
|
48
|
+
- **The backup log carries contacts.** Each push's `appData` now includes the
|
|
49
|
+
contacts table (`core/backup/contactsBackup.ts`): every contact by identity
|
|
50
|
+
key, removed ones too, with its label, star, cached handle and avatar, and
|
|
51
|
+
its dates; never the device-local ids. A restore writes them for the
|
|
52
|
+
restoring wallet's own user, and never rolls a newer edit back; restoring
|
|
53
|
+
from more than one device keeps everyone, each as last changed. An older
|
|
54
|
+
reader ignores the new field. Like the rest of `appData`, the snapshot only
|
|
55
|
+
travels on a push that carries an entity change, so a contact edit with no
|
|
56
|
+
payment after it reaches the log with the next payment.
|
|
57
|
+
- **Point-of-sale payment requests.** `core/pos/protocol.ts` is the wire
|
|
58
|
+
standard for a merchant's nearby payment: a signed `bsvpos1:` code that
|
|
59
|
+
either enrolls a cashier (`Invite`) or asks for one payment
|
|
60
|
+
(`MerchantRequest`: merchant, cashier, invoice, chain, expiry, the pairing
|
|
61
|
+
`session`, and optionally a `subtotal` and `tip` that must add up to the
|
|
62
|
+
session's amount). `sign`/`verify` use the `[2, 'bsv pos authorization']`
|
|
63
|
+
protocol, `encodePos`/`decodePos` do the framing and every field check, and
|
|
64
|
+
`decodePaymentRequest` turns a `bsvpos1:` code or a plain pairing code into
|
|
65
|
+
a `Session`. A merchant code fills the new `Session.merchantName`,
|
|
66
|
+
`merchantChain`, `merchantExpires`, `merchantSubtotal` and `merchantTip`
|
|
67
|
+
(verified display data, never part of the base pairing QR). `NearbyFlow`'s
|
|
68
|
+
payer scanner accepts these codes, names the merchant on the confirm step,
|
|
69
|
+
shows "sale + tip" when there is a tip, and refuses a request that has
|
|
70
|
+
expired or is for another network than the wallet's. Apps import it from
|
|
71
|
+
`core/pos/protocol` (not re-exported from `core/index.ts`).
|
|
72
|
+
- **`NearbyFlow` can be drawn by the host.** Three optional props, all
|
|
73
|
+
unset by default so the built-in screens are unchanged:
|
|
74
|
+
- `embedded` (payee with `initialRequest`): render inline inside a host
|
|
75
|
+
screen. While the request is live only the pairing code and its status
|
|
76
|
+
show, sized `qrSize`; a failure or an already-paid outcome opens full
|
|
77
|
+
screen in a modal, and its Cancel calls `onExit`. `onBusy` reports when a
|
|
78
|
+
payment is in hand, so the host does not remount or unmount the flow.
|
|
79
|
+
- `renderPayer` (payer): `confirm`, `sending`, `showCode` and `done`
|
|
80
|
+
renderers, each optional, handed the values and actions of that step
|
|
81
|
+
(`NearbyConfirm`, `NearbySending`, `NearbyShowCode`, `NearbyDone`, now
|
|
82
|
+
exported from `ui/index.ts`). The logic stays in the flow; a step without
|
|
83
|
+
a renderer keeps its built-in screen.
|
|
84
|
+
- `renderReceived` (payee): draw the "payment received" moment yourself
|
|
85
|
+
(`NearbyReceived`: amount, `amountText` for tokens, `broadcast`,
|
|
86
|
+
`verification`, `payerName`, `dismiss`). It replaces the built-in
|
|
87
|
+
overlay, so present it full screen and play your own sound.
|
|
88
|
+
- **`revokeConnection` is exported.** Signing a paired site out (stop serving
|
|
89
|
+
it at once, then tell it over the relay with a best-effort
|
|
90
|
+
`session_revoke`) moved out of `ConnectionsScreen` into
|
|
91
|
+
`core/services/revokeConnection.ts`, exported from `core/index.ts`, so an
|
|
92
|
+
app's own sign-ins screen revokes the same way. It takes the connection,
|
|
93
|
+
the permissions manager, `{ liveTopic, disconnect }` and optional `deps`
|
|
94
|
+
for tests; `ConnectionsScreen` behaves as before.
|
|
95
|
+
- **Contacts can be starred and removed.** `ContactRow` has `favourite` and
|
|
96
|
+
`removedAt`, and `ContactsStore` has `setFavourite`, `removeContact` and
|
|
97
|
+
`restoreContact`. A removed contact is hidden from `listContacts` and
|
|
98
|
+
`searchContacts` but kept, so adding the person again (or
|
|
99
|
+
`restoreContact`) brings them back; `getContact` still returns it, with
|
|
100
|
+
`removedAt` set. `deleteContact` still deletes the row.
|
|
101
|
+
- **The `contacts` table gains `favourite` and `removedAt`.**
|
|
102
|
+
`createTables` adds both through `ensureContactsColumns`: additive, with
|
|
103
|
+
defaults that mean "as before" (`favourite INTEGER NOT NULL DEFAULT 0`,
|
|
104
|
+
`removedAt TEXT`), so an existing database upgrades on the next open and an
|
|
105
|
+
app that never sets them sees its address book unchanged.
|
|
106
|
+
- **Start-up reads can begin before the app renders.**
|
|
107
|
+
`prewarmStartup()` in `core/context/startupPrewarm.ts` starts the secrets
|
|
108
|
+
migration and the profile and stored-config reads from the app's entry file
|
|
109
|
+
(once the crypto seams are installed). `LocalStorageProvider` and
|
|
110
|
+
`WalletContextProvider` take the reads in flight instead of starting them
|
|
111
|
+
in effects after the first screen has committed. An app that does not call
|
|
112
|
+
it behaves as before, and each prewarmed read is used once; a later run
|
|
113
|
+
(after logout) does its own.
|
|
114
|
+
- **A host-configurable minimum handle length.** `configureToolbox({
|
|
115
|
+
handleMinLength: 1 | 2 | 3 })` (default 3) sets the shortest handle
|
|
116
|
+
`isValidHandleFormat` accepts; `getHandleMinLength()` reads it. The rest of
|
|
117
|
+
the format is unchanged (a-z 0-9 . _ -, at most 32, starting and ending
|
|
118
|
+
with a letter or digit). A host that lowers it must use a registry that
|
|
119
|
+
accepts the shorter handles.
|
|
120
|
+
- **Payment links carry a note.** `peerpay:` links may carry a `note`
|
|
121
|
+
extension (BRC-125's extension rule, so other wallets ignore it).
|
|
122
|
+
`parsePeerPayURI`, `validatePeerPayURI`, `classifyScan` and the `handle`
|
|
123
|
+
pay target return it as `note`, cleaned by the new `cleanPeerPayNote`
|
|
124
|
+
(single line, control characters stripped, at most `PEERPAY_NOTE_MAX` = 120
|
|
125
|
+
characters), and `peerPayLinkFor` takes a trailing `note` argument to write
|
|
126
|
+
one.
|
|
127
|
+
- **A handle payment's note reaches the receiver.** The MessageBox client
|
|
128
|
+
rebuilds a payment from its token fields alone, which dropped the `note`
|
|
129
|
+
the sending side adds. `creditInbox` now puts the sender's note back on each
|
|
130
|
+
parsed payment (`withSenderNotes`) from the raw message.
|
|
131
|
+
- **A host sounds switch.** `sounds.setEnabled(false)` in
|
|
132
|
+
`core/hooks/useConfirmationSound.ts` silences every tone until it is turned
|
|
133
|
+
back on (on by default).
|
|
134
|
+
- **Export a chosen set of transactions.** `exportTransactionsAsCsv` takes an
|
|
135
|
+
optional `select(action)` filter (a period, a direction) and an optional
|
|
136
|
+
`fileName`, and the paging helper behind it is exported as
|
|
137
|
+
`listAllActions(wallet, adminOriginator)`. The existing three-argument call
|
|
138
|
+
is unchanged.
|
|
139
|
+
- **Shared helpers for host screens.** `core/profiles/removalProblems.ts`
|
|
140
|
+
(`removalProblemKeys`) maps a refused or failed profile removal to the
|
|
141
|
+
`profile_remove_*` i18n keys, so every app's Profile screen explains it the
|
|
142
|
+
same way; `core/identity/handleRegistry/profileKeys.ts` exports
|
|
143
|
+
`HANDLE_KV_KEY` and `DISPLAY_NAME_KV_KEY`, the storage keys of a wallet's
|
|
144
|
+
own profile, so a host that registers a handle itself reads and writes the
|
|
145
|
+
same entries as `ProfileScreen`; `core/net/trimTrailingSlashes.ts` is a
|
|
146
|
+
linear-time replacement for `s.replace(/\/+$/, '')`.
|
|
147
|
+
- **`WalletConfigScreen` takes `hideLogout`.** An app that forgets wallets its
|
|
148
|
+
own way and shows the screen only as developer tools can leave the Log Out
|
|
149
|
+
row out. Default false.
|
|
150
|
+
|
|
151
|
+
### Changed
|
|
152
|
+
|
|
153
|
+
- **iOS nearby payments step down AWDL, then BLE, then the QR code.** When
|
|
154
|
+
the AWDL link never came up, the payer now tries Bluetooth (if the payee's
|
|
155
|
+
code offered it and this device can) before showing the payment as a code.
|
|
156
|
+
Only a failure that proves not one byte left the device qualifies
|
|
157
|
+
(`failedBeforeConnect`, matching the native "no route to peer" text), so a
|
|
158
|
+
lost ack or a timeout after the link was up still goes straight to the QR
|
|
159
|
+
fountain: a second radio could deliver the frame twice into a payee race
|
|
160
|
+
that has already settled. `fallbackRadio(session, failed)` and
|
|
161
|
+
`failedBeforeConnect(error)` are exported from `core/index.ts` next to
|
|
162
|
+
`selectTransport`.
|
|
163
|
+
- **The payer skips AWDL when the payee was off Wi-Fi.** A payee that made
|
|
164
|
+
its code with a network probe that answered and found no Wi-Fi advertises
|
|
165
|
+
AWDL anyway (turning Wi-Fi off in Control Center leaves the radio up), but
|
|
166
|
+
AWDL between phones off a network fails in practice and cost the whole
|
|
167
|
+
connect timeout. `selectTransport` now passes over it in that case
|
|
168
|
+
(`peerKnownOffWifi` in `core/localpay/transport/select.ts`). A code with no
|
|
169
|
+
probe answer, or an older one with no hint bits, is not "off" and keeps the
|
|
170
|
+
AWDL rung.
|
|
171
|
+
- **Contacts come back from the address book without removed ones.**
|
|
172
|
+
`listContacts` and `searchContacts` leave out contacts with `removedAt` set
|
|
173
|
+
(see Added). `ContactRow.favourite` is a required boolean, so code that
|
|
174
|
+
builds a `ContactRow` or implements `ContactsStore` itself must supply it
|
|
175
|
+
and the three new methods.
|
|
176
|
+
- **Handle format check is length-driven.** `isValidHandleFormat` now tests
|
|
177
|
+
the length against `getHandleMinLength()` and the character shape
|
|
178
|
+
separately; with the default configuration it accepts exactly the same
|
|
179
|
+
3-32 character handles as before.
|
|
180
|
+
- **Trailing-slash trimming on URLs no longer backtracks.** Every
|
|
181
|
+
`replace(/\/+$/, '')` on a URL that can arrive from a link, QR code or other
|
|
182
|
+
app (backup, push, MessageBox, overlay, registry, `peerpay:` and
|
|
183
|
+
token-overlay comparison) now uses `trimTrailingSlashes`, removing a
|
|
184
|
+
quadratic-time pattern (CodeQL `js/polynomial-redos`). Results are
|
|
185
|
+
identical.
|
|
186
|
+
- **`ProfileScreen` and `ConnectionsScreen` use the shared helpers** above
|
|
187
|
+
instead of local copies; what they show is unchanged.
|
|
188
|
+
|
|
189
|
+
### Fixed
|
|
190
|
+
|
|
191
|
+
- **Short payment notes no longer fail the send.** A wallet action's
|
|
192
|
+
description must be at least 5 bytes and the validator does not trim, so a
|
|
193
|
+
note like "ok" made `createAction` fail on the nearby (BSV and token) and
|
|
194
|
+
address rails. The description is now space-padded to 5
|
|
195
|
+
(`core/localpay/build.ts`, `core/pay/rails/address.ts`). The padding is
|
|
196
|
+
also needed where the note goes through `@bsv/mandala` (its send and
|
|
197
|
+
receive notes); that is in the mandala package, not here. Until mandala
|
|
198
|
+
fixes it, apps must carry a `patch-package` patch for `@bsv/mandala` 0.4.1
|
|
199
|
+
that pads the description the same way.
|
|
200
|
+
|
|
201
|
+
|
|
3
202
|
## 0.15.2
|
|
4
203
|
|
|
5
204
|
### 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.
|
package/core/backup/restore.ts
CHANGED
|
@@ -37,6 +37,13 @@ export interface RestoreDeps {
|
|
|
37
37
|
* first chunk arrives.
|
|
38
38
|
*/
|
|
39
39
|
onProgress?: (chunks: number, total: number) => void
|
|
40
|
+
/**
|
|
41
|
+
* Called whenever the restore finishes a step that is not a chunk: ranking a candidate
|
|
42
|
+
* generation, and each page of the post-replay proof reconciliation. Carries nothing; it
|
|
43
|
+
* only says the restore is still working, so a caller waiting on it can tell a slow
|
|
44
|
+
* restore from a stuck one.
|
|
45
|
+
*/
|
|
46
|
+
onActivity?: () => void
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
export interface RestoreResult {
|
|
@@ -92,7 +99,16 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
|
|
|
92
99
|
}
|
|
93
100
|
|
|
94
101
|
const settings = await deps.storage.makeAvailable()
|
|
95
|
-
const chosen = await pickTarget(
|
|
102
|
+
const chosen = await pickTarget(
|
|
103
|
+
devices,
|
|
104
|
+
client,
|
|
105
|
+
wallet,
|
|
106
|
+
deps.chain,
|
|
107
|
+
settings,
|
|
108
|
+
deps.deviceId,
|
|
109
|
+
deps.generation,
|
|
110
|
+
deps.onActivity
|
|
111
|
+
)
|
|
96
112
|
|
|
97
113
|
// processSyncChunk's preconditions, which a fresh, just-migrated database does
|
|
98
114
|
// not meet: it does verifyTruthy(findUserByIdentityKey(identityKey)) and then
|
|
@@ -144,7 +160,8 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
|
|
|
144
160
|
if (chunks > reader.length) throw new Error('Backup replay did not acknowledge completion')
|
|
145
161
|
}
|
|
146
162
|
|
|
147
|
-
|
|
163
|
+
deps.onActivity?.()
|
|
164
|
+
await reconcileRestoredProofs(deps.storage, deps.onActivity)
|
|
148
165
|
return {
|
|
149
166
|
chunks,
|
|
150
167
|
deviceId: chosen.deviceId,
|
|
@@ -162,9 +179,10 @@ export async function restoreFromBackup (deps: RestoreDeps): Promise<RestoreResu
|
|
|
162
179
|
* which also reconciles notification IDs and preserves completed transactions.
|
|
163
180
|
* Run only after the entire log lands, before the wallet/monitor is published.
|
|
164
181
|
*/
|
|
165
|
-
async function reconcileRestoredProofs (storage: StorageExpoSQLite): Promise<void> {
|
|
182
|
+
async function reconcileRestoredProofs (storage: StorageExpoSQLite, onActivity?: () => void): Promise<void> {
|
|
166
183
|
const limit = 1
|
|
167
184
|
for (let offset = 0; ; offset += limit) {
|
|
185
|
+
if (offset > 0) onActivity?.()
|
|
168
186
|
// Page over every status so completing a request cannot shift the next
|
|
169
187
|
// page's offsets. A request may contain a large expanded inputBEEF, so
|
|
170
188
|
// retain only one request at a time while completion reloads its proof.
|
|
@@ -229,7 +247,9 @@ export async function pickTarget (
|
|
|
229
247
|
chain: BackupChain,
|
|
230
248
|
settings: TableSettings,
|
|
231
249
|
deviceId?: string,
|
|
232
|
-
generation?: number
|
|
250
|
+
generation?: number,
|
|
251
|
+
/** Called after each candidate is checked, readable or not (see RestoreDeps.onActivity). */
|
|
252
|
+
onActivity?: () => void
|
|
233
253
|
): Promise<PickedTarget> {
|
|
234
254
|
const candidates = deviceId != null ? devices.filter(d => d.deviceId === deviceId) : devices
|
|
235
255
|
if (candidates.length === 0) {
|
|
@@ -244,6 +264,7 @@ export async function pickTarget (
|
|
|
244
264
|
if (exact == null) throw new Error(`No backup found for generation ${generation}`)
|
|
245
265
|
const reader = readerFor(exact)
|
|
246
266
|
const verified = await reader.verifiedComplete()
|
|
267
|
+
onActivity?.()
|
|
247
268
|
return { deviceId: exact.deviceId, generation: exact.generation, verified, reader }
|
|
248
269
|
}
|
|
249
270
|
|
|
@@ -262,6 +283,7 @@ export async function pickTarget (
|
|
|
262
283
|
// and was never going to be chosen anyway — it is simply not verified.
|
|
263
284
|
verified = false
|
|
264
285
|
}
|
|
286
|
+
onActivity?.()
|
|
265
287
|
if (verified) return { deviceId: candidate.deviceId, generation: candidate.generation, verified: true, reader }
|
|
266
288
|
}
|
|
267
289
|
|
|
@@ -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'
|
|
@@ -60,6 +62,12 @@ export interface RestoreOnImportDeps {
|
|
|
60
62
|
* once per device, each restarting from its own generation's own total.
|
|
61
63
|
*/
|
|
62
64
|
onProgress?: (chunks: number, total: number) => void
|
|
65
|
+
/**
|
|
66
|
+
* Called whenever the restore finishes a step that is not a chunk: each candidate it
|
|
67
|
+
* ranks, before and during proof reconciliation, and before the coin review.
|
|
68
|
+
* See RestoreDeps.onActivity.
|
|
69
|
+
*/
|
|
70
|
+
onActivity?: () => void
|
|
63
71
|
/**
|
|
64
72
|
* After a successful replay, check that restored coins are still spendable.
|
|
65
73
|
* Awaited before this function resolves, but best-effort: a failure is logged and
|
|
@@ -110,7 +118,7 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
|
|
|
110
118
|
// manifest — the overwhelming common case — restores exactly as before.
|
|
111
119
|
const wallet = deriveBackupWallet(deps.primaryKey, deps.chain)
|
|
112
120
|
const settings = await deps.storage.makeAvailable()
|
|
113
|
-
const primary = await pickTarget(devices, client, wallet, deps.chain, settings)
|
|
121
|
+
const primary = await pickTarget(devices, client, wallet, deps.chain, settings, undefined, undefined, deps.onActivity)
|
|
114
122
|
|
|
115
123
|
const primaryResult = await restoreFromBackup({
|
|
116
124
|
storage: deps.storage,
|
|
@@ -121,7 +129,8 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
|
|
|
121
129
|
manifest: devices,
|
|
122
130
|
deviceId: primary.deviceId,
|
|
123
131
|
generation: primary.generation,
|
|
124
|
-
onProgress: deps.onProgress
|
|
132
|
+
onProgress: deps.onProgress,
|
|
133
|
+
onActivity: deps.onActivity
|
|
125
134
|
})
|
|
126
135
|
|
|
127
136
|
let chunks = primaryResult.chunks
|
|
@@ -142,7 +151,7 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
|
|
|
142
151
|
// rather than blindly taking its newest generation.
|
|
143
152
|
const otherDeviceIds = [...new Set(devices.map(d => d.deviceId))].filter(id => id !== primary.deviceId)
|
|
144
153
|
for (const deviceId of otherDeviceIds) {
|
|
145
|
-
const target = await pickTarget(devices, client, wallet, deps.chain, settings, deviceId)
|
|
154
|
+
const target = await pickTarget(devices, client, wallet, deps.chain, settings, deviceId, undefined, deps.onActivity)
|
|
146
155
|
const result = await restoreFromBackup({
|
|
147
156
|
storage: deps.storage,
|
|
148
157
|
primaryKey: deps.primaryKey,
|
|
@@ -152,7 +161,8 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
|
|
|
152
161
|
manifest: devices,
|
|
153
162
|
deviceId: target.deviceId,
|
|
154
163
|
generation: target.generation,
|
|
155
|
-
onProgress: deps.onProgress
|
|
164
|
+
onProgress: deps.onProgress,
|
|
165
|
+
onActivity: deps.onActivity
|
|
156
166
|
})
|
|
157
167
|
chunks += result.chunks
|
|
158
168
|
verified = verified && result.verified
|
|
@@ -167,9 +177,23 @@ export async function restoreOnImport (deps: RestoreOnImportDeps): Promise<Resto
|
|
|
167
177
|
// (see appData.ts's applyAppData docs).
|
|
168
178
|
if (appData !== undefined) {
|
|
169
179
|
await applyAppData(deps.storage, appData)
|
|
180
|
+
// the contacts, for this wallet's own local user (contactsBackup.ts); a failure here
|
|
181
|
+
// costs the contacts, never the restore
|
|
182
|
+
if (appData.contacts !== undefined) {
|
|
183
|
+
try {
|
|
184
|
+
const db = deps.storage.sqliteDb
|
|
185
|
+
if (db) {
|
|
186
|
+
const { user } = await deps.storage.findOrInsertUser(deps.identityKey)
|
|
187
|
+
await applyContacts(db as unknown as ContactsDb, user.userId, appData.contacts)
|
|
188
|
+
}
|
|
189
|
+
} catch (error) {
|
|
190
|
+
console.warn('[backup] contacts could not be restored', (error as Error)?.message)
|
|
191
|
+
}
|
|
192
|
+
}
|
|
170
193
|
}
|
|
171
194
|
|
|
172
195
|
if (deps.validateRestoredCoins) {
|
|
196
|
+
deps.onActivity?.()
|
|
173
197
|
try {
|
|
174
198
|
await deps.validateRestoredCoins()
|
|
175
199
|
} catch (error) {
|