@bsv/expo-wallet-toolbox 0.1.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/LICENSE.txt +28 -0
- package/README.md +512 -0
- package/assets/sounds/payment-receive.wav +0 -0
- package/assets/sounds/payment-send.wav +0 -0
- package/assets/sounds/vault-close.wav +0 -0
- package/assets/sounds/vault-open.wav +0 -0
- package/core/amountFormatHelpers.ts +330 -0
- package/core/backup/RemoteSyncReader.ts +94 -0
- package/core/backup/client.ts +111 -0
- package/core/backup/codec.ts +218 -0
- package/core/backup/constants.ts +88 -0
- package/core/backup/cursor.ts +138 -0
- package/core/backup/derive.ts +46 -0
- package/core/backup/deviceId.ts +33 -0
- package/core/backup/erase.ts +67 -0
- package/core/backup/preference.ts +33 -0
- package/core/backup/push.ts +295 -0
- package/core/backup/restore.ts +152 -0
- package/core/backup/restoreOnImport.ts +119 -0
- package/core/backup/status.ts +46 -0
- package/core/config.tsx +47 -0
- package/core/constants.ts +35 -0
- package/core/context/ExchangeRateContext.tsx +69 -0
- package/core/context/LocalStorageProvider.tsx +225 -0
- package/core/context/UserContext.tsx +129 -0
- package/core/context/VaultContext.tsx +79 -0
- package/core/context/WalletConnectionContext.tsx +454 -0
- package/core/context/WalletContext.tsx +2938 -0
- package/core/context/buildGeneration.ts +37 -0
- package/core/deviceTier.ts +89 -0
- package/core/diskSpace.ts +62 -0
- package/core/displayCurrencies.ts +56 -0
- package/core/headers/OfflineFirstChaintracks.ts +176 -0
- package/core/headers/checkpoints.ts +39 -0
- package/core/headers/fs.ts +119 -0
- package/core/headers/headerStore.ts +333 -0
- package/core/headers/prewarm.ts +36 -0
- package/core/headers/syncHeaders.ts +73 -0
- package/core/hooks/useConfirmationSound.ts +135 -0
- package/core/hooks/useHaptics.ts +51 -0
- package/core/hooks/usePermissionQueue.ts +69 -0
- package/core/i18n/translations.tsx +6692 -0
- package/core/index.ts +295 -0
- package/core/localpay/blePermissions.ts +32 -0
- package/core/localpay/build.ts +392 -0
- package/core/localpay/codec.ts +338 -0
- package/core/localpay/deviceCaps.ts +175 -0
- package/core/localpay/nearbyAdvisory.ts +32 -0
- package/core/localpay/nearbyPermissions.ts +34 -0
- package/core/localpay/pending.ts +385 -0
- package/core/localpay/pendingAborts.ts +67 -0
- package/core/localpay/qr.ts +16 -0
- package/core/localpay/session.ts +277 -0
- package/core/localpay/sessionPolicy.ts +5 -0
- package/core/localpay/transport/awdl.ts +11 -0
- package/core/localpay/transport/ble.ts +159 -0
- package/core/localpay/transport/nearby.ts +12 -0
- package/core/localpay/transport/race.ts +110 -0
- package/core/localpay/transport/select.ts +128 -0
- package/core/localpay/transport/socket.ts +244 -0
- package/core/localpay/types.ts +82 -0
- package/core/localpay/verify.ts +204 -0
- package/core/logging.config.ts +10 -0
- package/core/logging.ts +77 -0
- package/core/mnemonicWallet.ts +180 -0
- package/core/monitor/TaskBackupPush.ts +168 -0
- package/core/monitor/TaskCreditInbox.ts +116 -0
- package/core/monitor/TaskDrainOutbox.ts +122 -0
- package/core/monitor/TaskSendOffline.ts +123 -0
- package/core/monitor/unfailRetry.ts +116 -0
- package/core/net/chainMatch.ts +34 -0
- package/core/net/online.ts +34 -0
- package/core/offline/cancelParked.ts +56 -0
- package/core/offline/hold.ts +127 -0
- package/core/offline/order.ts +109 -0
- package/core/offline/payerHold.ts +144 -0
- package/core/offline/plan.ts +264 -0
- package/core/offline/queueGrace.ts +52 -0
- package/core/parsePeerPayURI.ts +119 -0
- package/core/pay/beefRepair.ts +106 -0
- package/core/pay/creditErrors.ts +46 -0
- package/core/pay/creditInbox.ts +202 -0
- package/core/pay/damagedInbox.ts +64 -0
- package/core/pay/proofNudge.ts +23 -0
- package/core/pay/provenTxFromBump.ts +31 -0
- package/core/pay/rails/address.ts +329 -0
- package/core/pay/rails/handle.ts +617 -0
- package/core/pay/rails/index.ts +197 -0
- package/core/pay/rails/nearby.ts +79 -0
- package/core/pay/receiveFocus.ts +13 -0
- package/core/pay/recordProof.ts +91 -0
- package/core/pay/refreshProofGuard.ts +34 -0
- package/core/pay/sweeper.ts +75 -0
- package/core/pay/tokenAmount.ts +18 -0
- package/core/pay/userError.ts +18 -0
- package/core/pay/watchlist.ts +126 -0
- package/core/peerpay/control.ts +122 -0
- package/core/peerpay/handleResendRequests.ts +475 -0
- package/core/peerpay/inboxAttempts.ts +33 -0
- package/core/peerpay/metadataDecryptor.ts +42 -0
- package/core/peerpay/offlineNacks.ts +96 -0
- package/core/peerpay/outbox.ts +209 -0
- package/core/peerpay/rebuildToken.ts +76 -0
- package/core/peerpay/resendBeef.ts +115 -0
- package/core/services/arcadeBroadcastProvider.ts +214 -0
- package/core/services/capWalletArgs.ts +99 -0
- package/core/services/exchangeRate.ts +63 -0
- package/core/services/secrets/envelope.ts +102 -0
- package/core/services/secrets/hkdf.ts +37 -0
- package/core/services/secrets/index.ts +63 -0
- package/core/services/secrets/kek.ts +274 -0
- package/core/services/secrets/migration.ts +188 -0
- package/core/services/secrets/policy.ts +120 -0
- package/core/services/secrets/storage.ts +54 -0
- package/core/services/secrets/store.ts +125 -0
- package/core/services/secrets/types.ts +85 -0
- package/core/services/usdFxRates.ts +101 -0
- package/core/services/vault/VaultKeyService.ts +312 -0
- package/core/services/vault/backupAttestation.ts +136 -0
- package/core/services/vault/ceremony.ts +972 -0
- package/core/services/vault/ceremonyHost.ts +46 -0
- package/core/services/vault/devMock.ts +22 -0
- package/core/services/vault/driver.ts +197 -0
- package/core/services/vault/guard.ts +90 -0
- package/core/services/vault/k1.ts +75 -0
- package/core/services/vault/mockYubiKey.ts +217 -0
- package/core/services/vault/random.ts +20 -0
- package/core/services/vault/sealing.ts +84 -0
- package/core/services/vault/session.ts +59 -0
- package/core/services/vault/transfers.ts +1151 -0
- package/core/services/vault/types.ts +109 -0
- package/core/services/vault/vaultDerivation.ts +152 -0
- package/core/services/vault/vaultPassphrase.ts +287 -0
- package/core/services/vault/vaultStore.ts +104 -0
- package/core/services/walletArgLimits.ts +234 -0
- package/core/services/walletServiceConfig.ts +170 -0
- package/core/storage/LocalStorageAdapter.ts +58 -0
- package/core/storage/README.md +391 -0
- package/core/storage/StorageExpoSQLite.ts +2008 -0
- package/core/storage/errors.ts +73 -0
- package/core/storage/index.ts +3 -0
- package/core/storage/methods/findSql.ts +286 -0
- package/core/storage/methods/historyNotes.ts +61 -0
- package/core/storage/methods/listActionsSql.ts +212 -0
- package/core/storage/methods/listOutputsSql.ts +211 -0
- package/core/storage/methods/offlineActions.ts +156 -0
- package/core/storage/methods/processOfflineActions.ts +503 -0
- package/core/storage/methods/reclaim.ts +135 -0
- package/core/storage/methods/reviewStatusSql.ts +167 -0
- package/core/storage/methods/unprovenWithoutReqSql.ts +26 -0
- package/core/storage/methods/walletBalanceSql.ts +55 -0
- package/core/storage/schema/createTables.ts +385 -0
- package/core/storage/skipQueuedAncestors.ts +29 -0
- package/core/storage/sqlUpdateValue.ts +12 -0
- package/core/stores/ConnectionStore.ts +71 -0
- package/core/theme/ThemeContext.tsx +182 -0
- package/core/theme/assertThemeContrast.ts +109 -0
- package/core/theme/motion.ts +50 -0
- package/core/theme/tokens.ts +232 -0
- package/core/theme/useThemeStyles.tsx +156 -0
- package/core/walletDbRegistry.ts +110 -0
- package/core/walletMonitor.ts +149 -0
- package/core/walletRepair/runWalletCheck.ts +195 -0
- package/core/walletRepair/shouldReleaseUtxo.ts +18 -0
- package/package.json +86 -0
- package/ui/backupShares.ts +367 -0
- package/ui/components/QRScanner.tsx +353 -0
- package/ui/components/pay/AddressReceive.tsx +507 -0
- package/ui/components/pay/AvailableBalance.tsx +61 -0
- package/ui/components/pay/HandleReceive.tsx +896 -0
- package/ui/components/pay/MessageBoxConfig.tsx +256 -0
- package/ui/components/pay/NearbyAdvisoryModal.tsx +111 -0
- package/ui/components/pay/NearbyFlow.tsx +2542 -0
- package/ui/components/pay/OfflineNotice.tsx +337 -0
- package/ui/components/pay/PayCellRow.tsx +101 -0
- package/ui/components/pay/PayForm.tsx +223 -0
- package/ui/components/pay/PaymentQrDisplay.tsx +105 -0
- package/ui/components/pay/PaymentSuccessOverlay.tsx +266 -0
- package/ui/components/pay/RecipientField.tsx +308 -0
- package/ui/components/pay/RequestHub.tsx +75 -0
- package/ui/components/pay/ResultBanner.tsx +69 -0
- package/ui/components/pay/UniversalSend.tsx +687 -0
- package/ui/components/pay/useRecipientInput.ts +270 -0
- package/ui/components/security/WalletLockNotice.tsx +138 -0
- package/ui/components/ui/AlertCard.tsx +223 -0
- package/ui/components/ui/AppLogo.tsx +166 -0
- package/ui/components/ui/BlurChrome.tsx +72 -0
- package/ui/components/ui/Celebration.tsx +84 -0
- package/ui/components/ui/ChoiceSheet.ts +69 -0
- package/ui/components/ui/CustomSafeArea.tsx +74 -0
- package/ui/components/ui/ErrorBoundary.tsx +154 -0
- package/ui/components/ui/GroupedList.tsx +125 -0
- package/ui/components/ui/IconButton.tsx +105 -0
- package/ui/components/ui/ListRow.tsx +197 -0
- package/ui/components/ui/PermissionSheet.tsx +920 -0
- package/ui/components/ui/PresenceRow.tsx +215 -0
- package/ui/components/ui/PressableScale.tsx +105 -0
- package/ui/components/ui/ScreenGradient.tsx +47 -0
- package/ui/components/ui/ScrollFade.tsx +76 -0
- package/ui/components/ui/Sheet.tsx +342 -0
- package/ui/components/ui/Toast.tsx +142 -0
- package/ui/components/ui/index.ts +8 -0
- package/ui/components/vault/EnrollWizard.tsx +627 -0
- package/ui/components/vault/PassphraseField.tsx +306 -0
- package/ui/components/vault/PhraseBackupSheet.tsx +227 -0
- package/ui/components/vault/VaultBackdrop.tsx +354 -0
- package/ui/components/vault/VaultCeremonySheet.tsx +327 -0
- package/ui/components/wallet/ActivityRow.tsx +408 -0
- package/ui/components/wallet/AmountDisplay.tsx +48 -0
- package/ui/components/wallet/AmountInput.tsx +256 -0
- package/ui/components/wallet/BackupReminderSheet.tsx +168 -0
- package/ui/components/wallet/Balance.tsx +144 -0
- package/ui/components/wallet/BiometricAdvisoryModal.tsx +133 -0
- package/ui/components/wallet/ImportFromBackupPrompt.tsx +93 -0
- package/ui/exportDatabases.ts +122 -0
- package/ui/exportTransactions.ts +129 -0
- package/ui/hooks/useOfflineNoticeActions.ts +136 -0
- package/ui/hooks/useOnline.ts +70 -0
- package/ui/hooks/useSpendableBalance.ts +58 -0
- package/ui/hooks/useVaultBalance.ts +50 -0
- package/ui/importDatabases.ts +170 -0
- package/ui/index.ts +136 -0
- package/ui/isImageUrl.ts +10 -0
- package/ui/printRecoveryShares.ts +93 -0
- package/ui/resolveIdentity.ts +125 -0
- package/ui/screens/ConnectionsScreen.tsx +438 -0
- package/ui/screens/LogsScreen.tsx +432 -0
- package/ui/screens/PairScreen.tsx +288 -0
- package/ui/screens/PayScreen.tsx +479 -0
- package/ui/screens/SettingsScreen.tsx +180 -0
- package/ui/screens/TrustScreen.tsx +831 -0
- package/ui/screens/VaultRecoverScreen.tsx +226 -0
- package/ui/screens/VaultScreen.tsx +423 -0
- package/ui/screens/VaultTransferScreen.tsx +293 -0
- package/ui/screens/WalletCheckScreen.tsx +539 -0
- package/ui/screens/WalletConfigScreen.tsx +1095 -0
- package/ui/screens/WalletHomeScreen.tsx +1597 -0
- package/ui/screens/homeBadges.ts +18 -0
- package/ui/txStatus.ts +79 -0
- package/ui/validateTrust.ts +44 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Encrypted chunk codec.
|
|
3
|
+
*
|
|
4
|
+
* Sync chunks are dominated by raw transaction bytes — TableProvenTx.rawTx,
|
|
5
|
+
* TableProvenTxReq.rawTx/inputBEEF, TableTransaction.rawTx/inputBEEF, merklePath — all
|
|
6
|
+
* typed `number[]`. A naive JSON.stringify renders each byte as up to four characters.
|
|
7
|
+
*
|
|
8
|
+
* The toolbox's own binary-aware serialiser is used, but on its own it does NOT help here:
|
|
9
|
+
* `binaryJsonReplacer` base64-encodes `Uint8Array` only, and the toolbox's own tables use
|
|
10
|
+
* `number[]`, so those fields would pass straight through as decimal arrays. Hence the
|
|
11
|
+
* packing pass below, which converts byte-valued arrays to `Uint8Array` first so the
|
|
12
|
+
* serialiser can compact them, and converts them back on the way in.
|
|
13
|
+
*
|
|
14
|
+
* The server stores opaque bytes and never parses a payload, so this format is a purely
|
|
15
|
+
* client-internal choice with no interop constraint.
|
|
16
|
+
*/
|
|
17
|
+
import type { CompletedProtoWallet } from '@bsv/sdk'
|
|
18
|
+
import { Utils } from '@bsv/sdk'
|
|
19
|
+
import type { SyncChunk } from '@bsv/wallet-toolbox-mobile/out/src/sdk/WalletStorage.interfaces'
|
|
20
|
+
import {
|
|
21
|
+
parseJsonRpc,
|
|
22
|
+
stringifyJsonRpc
|
|
23
|
+
} from '@bsv/wallet-toolbox-mobile/out/src/storage/remoting/BinaryJson'
|
|
24
|
+
import { BACKUP_PROTOCOL, backupKeyId, type BackupChain } from './constants'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Minimum length before a numeric array is worth packing as bytes.
|
|
28
|
+
*
|
|
29
|
+
* Below this the base64 envelope costs more than it saves, and short numeric arrays are
|
|
30
|
+
* usually ids rather than payloads.
|
|
31
|
+
*/
|
|
32
|
+
const PACK_MIN_LENGTH = 32
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Repack byte-valued numeric arrays as Uint8Array so the binary serialiser can base64 them.
|
|
36
|
+
*
|
|
37
|
+
* `binaryJsonReplacer` only base64-encodes `Uint8Array`, but every binary field on the
|
|
38
|
+
* toolbox's tables — rawTx, inputBEEF, merklePath — is typed `number[]`, so without this
|
|
39
|
+
* they serialise as decimal arrays at roughly four characters per byte. Packing first turns
|
|
40
|
+
* that into base64 at about 1.37, which is a threefold saving on a payload that is mostly
|
|
41
|
+
* transaction bytes and is pushed repeatedly over mobile data.
|
|
42
|
+
*
|
|
43
|
+
* The transform is lossless in both directions because `unpackBytes` converts every
|
|
44
|
+
* Uint8Array back to `number[]`. An array that merely looked byte-like — small integer ids,
|
|
45
|
+
* say — round-trips to exactly the values it started with.
|
|
46
|
+
*/
|
|
47
|
+
function packBytes (value: unknown): unknown {
|
|
48
|
+
if (Array.isArray(value)) {
|
|
49
|
+
const isByteArray =
|
|
50
|
+
value.length >= PACK_MIN_LENGTH &&
|
|
51
|
+
value.every(v => typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 255)
|
|
52
|
+
if (isByteArray) return new Uint8Array(value as number[])
|
|
53
|
+
return value.map(packBytes)
|
|
54
|
+
}
|
|
55
|
+
if (value != null && typeof value === 'object' && !(value instanceof Date)) {
|
|
56
|
+
const out: Record<string, unknown> = {}
|
|
57
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = packBytes(v)
|
|
58
|
+
return out
|
|
59
|
+
}
|
|
60
|
+
return value
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Cheap lower bound on a chunk's encoded size, in bytes.
|
|
65
|
+
*
|
|
66
|
+
* Walks the chunk applying packBytes' own byte-array rule and sums what those arrays cost
|
|
67
|
+
* once base64-encoded, plus every string's own length — with the blob columns compressed at
|
|
68
|
+
* rest, the remaining way a single record goes oversize is a string (a pre-scrub
|
|
69
|
+
* proven_tx_reqs.history carrying megabytes of EF hex in error notes). Everything else —
|
|
70
|
+
* keys, timestamps, numbers — is ignored, so the answer is an UNDERESTIMATE: a chunk this
|
|
71
|
+
* says is too big definitely is.
|
|
72
|
+
*
|
|
73
|
+
* Exists to be run BEFORE encodeChunk. Encrypting and then BRC-31-signing an oversized
|
|
74
|
+
* payload blocked the JS thread for ~50s per attempt on device; the point is to never do
|
|
75
|
+
* that work, not merely to avoid the failed upload at the end of it.
|
|
76
|
+
*/
|
|
77
|
+
export function estimateEncodedBytes (chunk: SyncChunk): number {
|
|
78
|
+
let bytes = 0
|
|
79
|
+
const walk = (value: unknown): void => {
|
|
80
|
+
if (typeof value === 'string') {
|
|
81
|
+
// JSON adds quotes and escapes, so the raw length stays a lower bound.
|
|
82
|
+
bytes += value.length
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
if (Array.isArray(value)) {
|
|
86
|
+
const isByteArray =
|
|
87
|
+
value.length >= PACK_MIN_LENGTH &&
|
|
88
|
+
value.every(v => typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 255)
|
|
89
|
+
// base64 is 4 characters per 3 bytes.
|
|
90
|
+
if (isByteArray) bytes += Math.ceil(value.length / 3) * 4
|
|
91
|
+
else value.forEach(walk)
|
|
92
|
+
return
|
|
93
|
+
}
|
|
94
|
+
if (value != null && typeof value === 'object' && !(value instanceof Date)) {
|
|
95
|
+
for (const v of Object.values(value as Record<string, unknown>)) walk(v)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
walk(chunk)
|
|
99
|
+
return bytes
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The table columns the toolbox types as Date. BinaryJson has no Date support:
|
|
103
|
+
* encode writes them as ISO strings, so decode must revive them — the merge
|
|
104
|
+
* entities call `.getTime()`/date arithmetic on them directly
|
|
105
|
+
* (EntityProvenTxReq.mergeExisting was the first to crash on a string). */
|
|
106
|
+
const DATE_KEYS = new Set(['created_at', 'updated_at'])
|
|
107
|
+
|
|
108
|
+
/** Inverse of packBytes: every Uint8Array becomes the `number[]` the toolbox
|
|
109
|
+
* expects, and date columns come back as Date instances. */
|
|
110
|
+
function unpackBytes (value: unknown, key?: string): unknown {
|
|
111
|
+
if (value instanceof Uint8Array) return Array.from(value)
|
|
112
|
+
if (typeof value === 'string' && key != null && DATE_KEYS.has(key)) {
|
|
113
|
+
const d = new Date(value)
|
|
114
|
+
return Number.isNaN(d.getTime()) ? value : d
|
|
115
|
+
}
|
|
116
|
+
if (Array.isArray(value)) return value.map(v => unpackBytes(v))
|
|
117
|
+
if (value != null && typeof value === 'object' && !(value instanceof Date)) {
|
|
118
|
+
const out: Record<string, unknown> = {}
|
|
119
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = unpackBytes(v, k)
|
|
120
|
+
return out
|
|
121
|
+
}
|
|
122
|
+
return value
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Serialise and encrypt a sync chunk.
|
|
127
|
+
*
|
|
128
|
+
* `counterparty: 'self'` is the entire zero-knowledge property. With 'self' the symmetric
|
|
129
|
+
* key comes from the wallet's own key material and nobody else can derive it; naming the
|
|
130
|
+
* server as counterparty instead would let the server decrypt via ECDH. One enum value
|
|
131
|
+
* decides it.
|
|
132
|
+
*
|
|
133
|
+
* The chain enters twice, deliberately. The keyID folds it into the encryption key, so a
|
|
134
|
+
* blob written on one network cannot decrypt on another at all. The plaintext also carries
|
|
135
|
+
* a `chain` label, which decodeChunk asserts — belt and braces so that even a future
|
|
136
|
+
* derivation mistake that collapsed the keys back together could not cross-restore.
|
|
137
|
+
*/
|
|
138
|
+
export async function encodeChunk (
|
|
139
|
+
wallet: CompletedProtoWallet,
|
|
140
|
+
chunk: SyncChunk,
|
|
141
|
+
chain: BackupChain
|
|
142
|
+
): Promise<number[]> {
|
|
143
|
+
const json = stringifyJsonRpc({ chain, chunk: packBytes(chunk) }, true)
|
|
144
|
+
const { ciphertext } = await wallet.encrypt({
|
|
145
|
+
plaintext: Utils.toArray(json, 'utf8'),
|
|
146
|
+
protocolID: BACKUP_PROTOCOL,
|
|
147
|
+
keyID: backupKeyId(chain),
|
|
148
|
+
counterparty: 'self'
|
|
149
|
+
})
|
|
150
|
+
return ciphertext
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Decrypt and parse a sync chunk. Throws if the ciphertext was not written by this key,
|
|
155
|
+
* or if the decrypted payload's chain label disagrees with the chain being restored.
|
|
156
|
+
*/
|
|
157
|
+
export async function decodeChunk (
|
|
158
|
+
wallet: CompletedProtoWallet,
|
|
159
|
+
ciphertext: number[],
|
|
160
|
+
chain: BackupChain
|
|
161
|
+
): Promise<SyncChunk> {
|
|
162
|
+
const { plaintext } = await wallet.decrypt({
|
|
163
|
+
ciphertext,
|
|
164
|
+
protocolID: BACKUP_PROTOCOL,
|
|
165
|
+
keyID: backupKeyId(chain),
|
|
166
|
+
counterparty: 'self'
|
|
167
|
+
})
|
|
168
|
+
const envelope = parseJsonRpc(Utils.toUTF8(plaintext), true) as { chain?: unknown, chunk?: unknown }
|
|
169
|
+
if (envelope?.chain !== chain) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
`backup blob is labeled for chain '${String(envelope?.chain)}' but '${chain}' was expected — refusing to restore across networks`
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
return unpackBytes(envelope.chunk) as SyncChunk
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The twelve entity arrays a SyncChunk carries, in the protocol's dependency order. */
|
|
178
|
+
export const CHUNK_ENTITIES = [
|
|
179
|
+
'provenTxs',
|
|
180
|
+
'provenTxReqs',
|
|
181
|
+
'outputBaskets',
|
|
182
|
+
'txLabels',
|
|
183
|
+
'outputTags',
|
|
184
|
+
'transactions',
|
|
185
|
+
'txLabelMaps',
|
|
186
|
+
'commissions',
|
|
187
|
+
'outputs',
|
|
188
|
+
'outputTagMaps',
|
|
189
|
+
'certificates',
|
|
190
|
+
'certificateFields'
|
|
191
|
+
] as const
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* True when a chunk carries no records at all.
|
|
195
|
+
*
|
|
196
|
+
* The toolbox treats an all-empty chunk as the completion sentinel, so this doubles as
|
|
197
|
+
* "nothing left to push" and "restore is finished".
|
|
198
|
+
*/
|
|
199
|
+
export function isEmptyChunk (chunk: SyncChunk): boolean {
|
|
200
|
+
const c = chunk as unknown as Record<string, unknown[] | undefined>
|
|
201
|
+
return CHUNK_ENTITIES.every(name => (c[name]?.length ?? 0) === 0)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* An all-empty chunk with every entity array present.
|
|
206
|
+
*
|
|
207
|
+
* All twelve must exist as arrays: the toolbox's consumer loops forever on an `undefined`
|
|
208
|
+
* entity array rather than treating it as empty.
|
|
209
|
+
*/
|
|
210
|
+
export function emptyChunk (from: string, to: string, userIdentityKey: string): SyncChunk {
|
|
211
|
+
const chunk: Record<string, unknown> = {
|
|
212
|
+
fromStorageIdentityKey: from,
|
|
213
|
+
toStorageIdentityKey: to,
|
|
214
|
+
userIdentityKey
|
|
215
|
+
}
|
|
216
|
+
for (const name of CHUNK_ENTITIES) chunk[name] = []
|
|
217
|
+
return chunk as unknown as SyncChunk
|
|
218
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Constants for the encrypted wallet backup log.
|
|
3
|
+
*
|
|
4
|
+
* @see docs/superpowers/specs/2026-08-14-encrypted-wallet-backup-log-design.md
|
|
5
|
+
*/
|
|
6
|
+
import type { WalletProtocol } from '@bsv/sdk'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The networks a wallet can run on, as WalletContext names them. Each gets its own backup
|
|
10
|
+
* derivation and therefore its own server account — see backupKeyId.
|
|
11
|
+
*/
|
|
12
|
+
export type BackupChain = 'main' | 'test' | 'teratest'
|
|
13
|
+
export const BACKUP_CHAINS: readonly BackupChain[] = ['main', 'test', 'teratest'] as const
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* FROZEN. Do not change the protocol tuple or the keyID scheme, ever.
|
|
17
|
+
*
|
|
18
|
+
* Restore has nothing but the user's seed to work from, so these must not vary by install,
|
|
19
|
+
* device, build, or randomness. Changing them orphans every backup ever written, with no
|
|
20
|
+
* error surfaced to anyone — the pseudonym simply becomes a different account holding no
|
|
21
|
+
* data.
|
|
22
|
+
*
|
|
23
|
+
* NOTE: in TypeScript `WalletProtocol` is a TUPLE `[SecurityLevel, string]`, not the
|
|
24
|
+
* `{securityLevel, protocol}` struct the Go SDK uses.
|
|
25
|
+
*
|
|
26
|
+
* Protocol names are validated at runtime: 5-400 chars, /^[a-z0-9 ]+$/, no double spaces,
|
|
27
|
+
* and must not end in " protocol".
|
|
28
|
+
*/
|
|
29
|
+
export const BACKUP_PROTOCOL: WalletProtocol = [2, 'wallet backup log']
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Per-network keyID.
|
|
33
|
+
*
|
|
34
|
+
* Folding the chain into the derivation is what makes cross-network restore impossible
|
|
35
|
+
* rather than merely filtered: one seed lands on three unrelated pseudonyms (three server
|
|
36
|
+
* accounts, so a testnet wallet's manifest never even lists mainnet blobs) and three
|
|
37
|
+
* unrelated encryption keys (so a mainnet blob would not decrypt on testnet regardless).
|
|
38
|
+
*/
|
|
39
|
+
export function backupKeyId (chain: BackupChain): string {
|
|
40
|
+
return `1 ${chain}`
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Delta chunk sizing.
|
|
45
|
+
*
|
|
46
|
+
* The protocol default `maxRoughSize` is 10,000,000, which is far too large to push from a
|
|
47
|
+
* phone on cellular — and the toolbox's own size estimator re-marshals the accumulating
|
|
48
|
+
* chunk on every page, so large values are quadratic. 512 KB of JSON comfortably encrypts
|
|
49
|
+
* to under the server's 1 MiB cap.
|
|
50
|
+
*/
|
|
51
|
+
export const MAX_ROUGH_SIZE = 512_000
|
|
52
|
+
export const MAX_ITEMS = 200
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Start a fresh full snapshot once a generation exceeds this many chunks.
|
|
56
|
+
*
|
|
57
|
+
* An append-only delta log grows without bound, because soft deletes mean nothing ever
|
|
58
|
+
* shrinks. Rotating bounds both server storage per user and restore time. The number is a
|
|
59
|
+
* starting estimate and wants measuring against a real wallet's growth.
|
|
60
|
+
*/
|
|
61
|
+
export const GENERATION_CHUNK_THRESHOLD = 200
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Floor between push passes.
|
|
65
|
+
*
|
|
66
|
+
* The monitor loop ticks roughly every five seconds and runs its tasks back-to-back with no
|
|
67
|
+
* yielding, so pushing on every tick would burn battery and compete with the UI for the JS
|
|
68
|
+
* thread.
|
|
69
|
+
*/
|
|
70
|
+
export const MIN_PUSH_INTERVAL_MS = 60_000
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Historic server blob cap, kept as a conservative reference for tests.
|
|
74
|
+
*
|
|
75
|
+
* The live cap comes from the server itself — GET /v1/limits, surfaced as
|
|
76
|
+
* `client.limits().maxBlobBytes` (200 MiB since the transaction-storage-capacity
|
|
77
|
+
* work) — and the push gate uses that, not this. Chunk sizing still aims well
|
|
78
|
+
* under this old 1 MiB figure because small chunks are what a phone on
|
|
79
|
+
* cellular wants regardless of what the server would accept.
|
|
80
|
+
*/
|
|
81
|
+
export const MAX_BLOB_BYTES = 1 << 20
|
|
82
|
+
|
|
83
|
+
/** AsyncStorage keys. */
|
|
84
|
+
export const DEVICE_ID_KEY = 'backupDeviceId'
|
|
85
|
+
// The chain is redundant with the pseudonym (which already differs per chain) but explicit:
|
|
86
|
+
// a cursor must never be consulted for the wrong network's database.
|
|
87
|
+
export const cursorKey = (chain: BackupChain, pseudonym: string, deviceId: string): string =>
|
|
88
|
+
`backupCursor-${chain}-${pseudonym}-${deviceId}`
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push cursor.
|
|
3
|
+
*
|
|
4
|
+
* The toolbox normally keeps sync state on the *writer* — `EntitySyncState` is loaded from
|
|
5
|
+
* whatever storage is receiving the data. Our writer is an opaque blob log that holds no
|
|
6
|
+
* state at all, so the client keeps the equivalent bookkeeping here.
|
|
7
|
+
*
|
|
8
|
+
* The semantics mirror `EntitySyncState` exactly, because a divergence would either skip
|
|
9
|
+
* records (a silent hole in a restore) or resend them forever:
|
|
10
|
+
*
|
|
11
|
+
* · `offsets` are per-entity counts of items already consumed *within the current `since`
|
|
12
|
+
* window*, and grow as chunks are taken.
|
|
13
|
+
* · When a chunk comes back completely empty the window is exhausted: `since` advances to
|
|
14
|
+
* the greatest `updated_at` seen, and every offset resets to zero.
|
|
15
|
+
*/
|
|
16
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
17
|
+
import { cursorKey, type BackupChain } from './constants'
|
|
18
|
+
|
|
19
|
+
/** The twelve entity names used by `offsets`, singular and camelCase, as the toolbox emits them. */
|
|
20
|
+
export const ENTITY_NAMES = [
|
|
21
|
+
'provenTx',
|
|
22
|
+
'outputBasket',
|
|
23
|
+
'outputTag',
|
|
24
|
+
'txLabel',
|
|
25
|
+
'transaction',
|
|
26
|
+
'output',
|
|
27
|
+
'txLabelMap',
|
|
28
|
+
'outputTagMap',
|
|
29
|
+
'certificate',
|
|
30
|
+
'certificateField',
|
|
31
|
+
'commission',
|
|
32
|
+
'provenTxReq'
|
|
33
|
+
] as const
|
|
34
|
+
|
|
35
|
+
export type EntityName = (typeof ENTITY_NAMES)[number]
|
|
36
|
+
|
|
37
|
+
/** Maps an offset entity name to its plural array on a SyncChunk. */
|
|
38
|
+
export const ENTITY_TO_CHUNK_ARRAY: Record<EntityName, string> = {
|
|
39
|
+
provenTx: 'provenTxs',
|
|
40
|
+
outputBasket: 'outputBaskets',
|
|
41
|
+
outputTag: 'outputTags',
|
|
42
|
+
txLabel: 'txLabels',
|
|
43
|
+
transaction: 'transactions',
|
|
44
|
+
output: 'outputs',
|
|
45
|
+
txLabelMap: 'txLabelMaps',
|
|
46
|
+
outputTagMap: 'outputTagMaps',
|
|
47
|
+
certificate: 'certificates',
|
|
48
|
+
certificateField: 'certificateFields',
|
|
49
|
+
commission: 'commissions',
|
|
50
|
+
provenTxReq: 'provenTxReqs'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface PushCursor {
|
|
54
|
+
/** ISO timestamp; only records updated at or after this are considered. */
|
|
55
|
+
since?: string
|
|
56
|
+
/** Per-entity consumed counts within the current `since` window. */
|
|
57
|
+
offsets: Record<EntityName, number>
|
|
58
|
+
/** Greatest `updated_at` seen in this window; becomes `since` when the window closes. */
|
|
59
|
+
maxUpdatedAt?: string
|
|
60
|
+
/** Current generation. Generations are full snapshots; older ones get pruned. */
|
|
61
|
+
generation: number
|
|
62
|
+
/** Sequence of the last chunk appended in this generation. */
|
|
63
|
+
seq: number
|
|
64
|
+
/** sha256 of the last appended chunk, chaining the log so gaps are detectable. */
|
|
65
|
+
prevSha256?: string
|
|
66
|
+
/** Chunks appended in this generation, used to decide when to rotate. */
|
|
67
|
+
chunksInGeneration: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function freshCursor (generation = 1): PushCursor {
|
|
71
|
+
return {
|
|
72
|
+
since: undefined,
|
|
73
|
+
offsets: zeroOffsets(),
|
|
74
|
+
maxUpdatedAt: undefined,
|
|
75
|
+
generation,
|
|
76
|
+
seq: 0,
|
|
77
|
+
prevSha256: undefined,
|
|
78
|
+
chunksInGeneration: 0
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function zeroOffsets (): Record<EntityName, number> {
|
|
83
|
+
const out = {} as Record<EntityName, number>
|
|
84
|
+
for (const name of ENTITY_NAMES) out[name] = 0
|
|
85
|
+
return out
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Offsets in the array-of-pairs shape `RequestSyncChunkArgs` expects. */
|
|
89
|
+
// eslint-disable-next-line @typescript-eslint/array-type -- matches the SDK's own signature
|
|
90
|
+
export function offsetsToArgs (offsets: Record<EntityName, number>): Array<{ name: string, offset: number }> {
|
|
91
|
+
return ENTITY_NAMES.map(name => ({ name, offset: offsets[name] ?? 0 }))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function loadCursor (chain: BackupChain, pseudonym: string, deviceId: string): Promise<PushCursor> {
|
|
95
|
+
const raw = await AsyncStorage.getItem(cursorKey(chain, pseudonym, deviceId))
|
|
96
|
+
if (raw == null) return freshCursor()
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(raw) as Partial<PushCursor>
|
|
100
|
+
return {
|
|
101
|
+
since: parsed.since,
|
|
102
|
+
// Merge over a zeroed base so a cursor written by an older build, before a new
|
|
103
|
+
// entity existed, does not produce an undefined offset.
|
|
104
|
+
offsets: { ...zeroOffsets(), ...(parsed.offsets ?? {}) },
|
|
105
|
+
maxUpdatedAt: parsed.maxUpdatedAt,
|
|
106
|
+
generation: parsed.generation ?? 1,
|
|
107
|
+
seq: parsed.seq ?? 0,
|
|
108
|
+
prevSha256: parsed.prevSha256,
|
|
109
|
+
chunksInGeneration: parsed.chunksInGeneration ?? 0
|
|
110
|
+
}
|
|
111
|
+
} catch {
|
|
112
|
+
// A corrupt cursor must not wedge backups forever. Starting a fresh generation costs
|
|
113
|
+
// one full snapshot and is always safe.
|
|
114
|
+
return freshCursor()
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function saveCursor (chain: BackupChain, pseudonym: string, deviceId: string, c: PushCursor): Promise<void> {
|
|
119
|
+
await AsyncStorage.setItem(cursorKey(chain, pseudonym, deviceId), JSON.stringify(c))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function clearCursor (chain: BackupChain, pseudonym: string, deviceId: string): Promise<void> {
|
|
123
|
+
await AsyncStorage.removeItem(cursorKey(chain, pseudonym, deviceId))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Drop every cursor belonging to one pseudonym, whichever device wrote it.
|
|
128
|
+
*
|
|
129
|
+
* For erasure: after the server's log is gone, a cursor still claiming "generation 3, seq 9"
|
|
130
|
+
* describes a log that no longer exists, and the next append would conflict with a head the
|
|
131
|
+
* server has never heard of instead of starting a fresh generation. Scoped by prefix so a
|
|
132
|
+
* second wallet on the same device keeps its own bookkeeping.
|
|
133
|
+
*/
|
|
134
|
+
export async function clearCursorsForPseudonym (chain: BackupChain, pseudonym: string): Promise<void> {
|
|
135
|
+
const prefix = cursorKey(chain, pseudonym, '')
|
|
136
|
+
const keys = (await AsyncStorage.getAllKeys()).filter(k => k.startsWith(prefix))
|
|
137
|
+
if (keys.length > 0) await AsyncStorage.multiRemove(keys)
|
|
138
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backup identity derivation.
|
|
3
|
+
*
|
|
4
|
+
* One derived key serves two purposes: it signs every auth proof, so the server
|
|
5
|
+
* only ever sees a pseudonym rather than the wallet's real identity key; and it is the
|
|
6
|
+
* encryption key, used with counterparty 'self' so the server cannot decrypt what it
|
|
7
|
+
* stores. Both properties are chosen by the client — the server is merely unable to help.
|
|
8
|
+
*
|
|
9
|
+
* The chain is part of the derivation (via the keyID), so each network gets an unrelated
|
|
10
|
+
* pseudonym and an unrelated encryption key. That is the network-separation property:
|
|
11
|
+
* a testnet wallet cannot list, download, or decrypt mainnet backups, and vice versa.
|
|
12
|
+
*/
|
|
13
|
+
import { CompletedProtoWallet, KeyDeriver, PrivateKey } from '@bsv/sdk'
|
|
14
|
+
import { BACKUP_PROTOCOL, backupKeyId, type BackupChain } from './constants'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Derive the backup-only wallet from the wallet's primary key (m/0'/0') and the network.
|
|
18
|
+
*
|
|
19
|
+
* primaryKey, NOT rootKey. A wallet restored from printed backup shares recovers only the
|
|
20
|
+
* m/0'/0' WIF and has no rootKey at all, so deriving from rootKey would leave exactly that
|
|
21
|
+
* cohort unable to decrypt their own backups — the cohort this feature most helps.
|
|
22
|
+
*
|
|
23
|
+
* Using a dedicated wallet rather than the app's main one also keeps blob encryption clear
|
|
24
|
+
* of WalletPermissionsManager, so it can never raise a protocol-permission prompt or a
|
|
25
|
+
* spending-authorisation gate.
|
|
26
|
+
*/
|
|
27
|
+
export function deriveBackupWallet (primaryKey: number[], chain: BackupChain): CompletedProtoWallet {
|
|
28
|
+
return new CompletedProtoWallet(deriveBackupKey(primaryKey, chain))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The private key behind the backup identity for one network. */
|
|
32
|
+
export function deriveBackupKey (primaryKey: number[], chain: BackupChain): PrivateKey {
|
|
33
|
+
const deriver = new KeyDeriver(new PrivateKey(primaryKey))
|
|
34
|
+
return deriver.derivePrivateKey(BACKUP_PROTOCOL, backupKeyId(chain), 'self')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The server-visible account address: a compressed public key in DER hex.
|
|
39
|
+
*
|
|
40
|
+
* This is never the wallet's identity key, and the server has no other way to address an
|
|
41
|
+
* account — there is no identity field anywhere in the API. One seed yields a DIFFERENT
|
|
42
|
+
* pseudonym per network, so mainnet and testnet logs live in separate server accounts.
|
|
43
|
+
*/
|
|
44
|
+
export function backupPseudonym (primaryKey: number[], chain: BackupChain): string {
|
|
45
|
+
return deriveBackupKey(primaryKey, chain).toPublicKey().toString()
|
|
46
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-install device identifier for the backup log.
|
|
3
|
+
*
|
|
4
|
+
* Opaque and locally generated — it is not a hardware id and carries no device
|
|
5
|
+
* information. It exists so that two devices restoring the same wallet keep separate,
|
|
6
|
+
* independently sequenced logs rather than fighting over one sequence.
|
|
7
|
+
*/
|
|
8
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
9
|
+
import { Random, Utils } from '@bsv/sdk'
|
|
10
|
+
import { DEVICE_ID_KEY } from './constants'
|
|
11
|
+
|
|
12
|
+
let cached: string | null = null
|
|
13
|
+
|
|
14
|
+
/** 32 lowercase hex characters, matching the server's device-id pattern. */
|
|
15
|
+
export async function getDeviceId (): Promise<string> {
|
|
16
|
+
if (cached != null) return cached
|
|
17
|
+
|
|
18
|
+
const existing = await AsyncStorage.getItem(DEVICE_ID_KEY)
|
|
19
|
+
if (existing != null && /^[a-f0-9]{32}$/.test(existing)) {
|
|
20
|
+
cached = existing
|
|
21
|
+
return existing
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const fresh = Utils.toHex(Random(16))
|
|
25
|
+
await AsyncStorage.setItem(DEVICE_ID_KEY, fresh)
|
|
26
|
+
cached = fresh
|
|
27
|
+
return fresh
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Test seam. */
|
|
31
|
+
export function resetDeviceIdCache (): void {
|
|
32
|
+
cached = null
|
|
33
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Erasure on request — the GDPR Article 17 path for the encrypted backup log.
|
|
3
|
+
*
|
|
4
|
+
* Three steps, in this order, and the order is the correctness argument:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Opt out of pushing.** Written FIRST. The monitor can run a push pass at any moment,
|
|
7
|
+
* so with the opt-out written afterwards a pass landing between the delete and the flag
|
|
8
|
+
* would append a fresh chunk — leaving wallet data on a server that has just reported a
|
|
9
|
+
* successful erasure. Doing it first closes that window entirely.
|
|
10
|
+
* 2. **Delete server-side.** `DELETE /v1/account` removes every generation for this
|
|
11
|
+
* pseudonym across every device, ignoring the retention guard that `pruneGeneration`
|
|
12
|
+
* enforces. Errors propagate: a failed erasure must never be reported as done.
|
|
13
|
+
* 3. **Clear local cursors.** Only on success. A cursor describing a log the server no
|
|
14
|
+
* longer holds would make a later append conflict against a head that does not exist;
|
|
15
|
+
* cleared, a re-enabled backup starts a fresh generation from a full snapshot.
|
|
16
|
+
*
|
|
17
|
+
* The opt-out deliberately SURVIVES a failed erasure. It was a deliberate act by someone who
|
|
18
|
+
* wants their data gone, and silently resuming uploads because the delete failed is the
|
|
19
|
+
* opposite of what they asked for.
|
|
20
|
+
*
|
|
21
|
+
* What this does not touch: the wallet itself. Coins, keys, recovery phrase and local
|
|
22
|
+
* database are all untouched — this removes the server's copy only. The cost is that a new
|
|
23
|
+
* device can no longer be fully restored, which is why the caller confirms first.
|
|
24
|
+
*/
|
|
25
|
+
import { BackupClient } from './client'
|
|
26
|
+
import type { BackupChain } from './constants'
|
|
27
|
+
import { clearCursorsForPseudonym } from './cursor'
|
|
28
|
+
import { backupPseudonym } from './derive'
|
|
29
|
+
import { setBackupPushEnabled } from './preference'
|
|
30
|
+
|
|
31
|
+
export interface EraseDeps {
|
|
32
|
+
/** The wallet's m/0'/0' key. Derives the pseudonym whose data is erased. */
|
|
33
|
+
primaryKey: number[]
|
|
34
|
+
/** The network whose backup account is erased. Each network is a separate account. */
|
|
35
|
+
chain: BackupChain
|
|
36
|
+
/** Supply exactly one of these. */
|
|
37
|
+
baseUrl?: string
|
|
38
|
+
client?: BackupClient
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface EraseResult {
|
|
42
|
+
/** Blobs the server removed. Zero is a success: nothing was there. */
|
|
43
|
+
deleted: number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function eraseRemoteBackup (deps: EraseDeps): Promise<EraseResult> {
|
|
47
|
+
const client = resolveClient(deps)
|
|
48
|
+
|
|
49
|
+
// Step 1 — before anything is deleted. See the module doc.
|
|
50
|
+
await setBackupPushEnabled(false)
|
|
51
|
+
|
|
52
|
+
// Step 2 — throws on any server refusal, leaving the local cursors intact.
|
|
53
|
+
const { deleted } = await client.deleteAccount()
|
|
54
|
+
|
|
55
|
+
// Step 3 — only now that the server really has nothing.
|
|
56
|
+
await clearCursorsForPseudonym(deps.chain, backupPseudonym(deps.primaryKey, deps.chain))
|
|
57
|
+
|
|
58
|
+
return { deleted }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function resolveClient (deps: EraseDeps): BackupClient {
|
|
62
|
+
if (deps.client != null) return deps.client
|
|
63
|
+
if (deps.baseUrl == null || deps.baseUrl === '') {
|
|
64
|
+
throw new Error('eraseRemoteBackup requires either a client or a baseUrl')
|
|
65
|
+
}
|
|
66
|
+
return new BackupClient(deps.baseUrl, deps.primaryKey, deps.chain)
|
|
67
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The user's opt-out for pushing to the backup server.
|
|
3
|
+
*
|
|
4
|
+
* ON by default, and every ambiguous case resolves to ON: a missing key, an unreadable
|
|
5
|
+
* store, an unrecognised value. Opting out is the only thing that turns pushing off, and it
|
|
6
|
+
* writes 'false' explicitly — absence can never mean "off", because a wallet that quietly
|
|
7
|
+
* stopped backing up (and only found out when it needed a restore) is exactly the outcome
|
|
8
|
+
* the backup log exists to prevent.
|
|
9
|
+
*
|
|
10
|
+
* The opt-out stops pushing only. Restoring on a new device still works: a log already on
|
|
11
|
+
* the server stays readable, and `restoreOnImport` never consults this.
|
|
12
|
+
*
|
|
13
|
+
* Not stored in wallet settings: those live in the wallet database, which is itself what
|
|
14
|
+
* gets backed up, and the flag has to be readable by a push pass that runs before/without
|
|
15
|
+
* the settings manager.
|
|
16
|
+
*/
|
|
17
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
18
|
+
|
|
19
|
+
export const BACKUP_PUSH_ENABLED_KEY = 'backupPushEnabled'
|
|
20
|
+
|
|
21
|
+
/** True unless the user has explicitly opted out. Never throws. */
|
|
22
|
+
export async function isBackupPushEnabled (): Promise<boolean> {
|
|
23
|
+
try {
|
|
24
|
+
return (await AsyncStorage.getItem(BACKUP_PUSH_ENABLED_KEY)) !== 'false'
|
|
25
|
+
} catch {
|
|
26
|
+
// Fail towards backing up. The alternative silently abandons the user's history.
|
|
27
|
+
return true
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function setBackupPushEnabled (enabled: boolean): Promise<void> {
|
|
32
|
+
await AsyncStorage.setItem(BACKUP_PUSH_ENABLED_KEY, enabled ? 'true' : 'false')
|
|
33
|
+
}
|