@bsv/expo-wallet-toolbox 0.12.0 → 0.14.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 +118 -0
- package/core/backup/erase.ts +7 -1
- package/core/backup/preference.ts +12 -4
- package/core/backup/push.ts +8 -1
- package/core/backup/status.ts +6 -2
- package/core/context/WalletContext.tsx +855 -238
- package/core/i18n/translations.tsx +376 -0
- package/core/identity/handleRegistry/registration.ts +57 -3
- package/core/index.ts +24 -1
- package/core/mandala/createRuntime.ts +3 -3
- package/core/mandala/runtime.ts +7 -2
- package/core/mnemonicWallet.ts +46 -40
- package/core/monitor/MonitorSupervisor.ts +35 -1
- package/core/monitor/TaskCreditInbox.ts +24 -0
- package/core/pay/rails/handle.ts +4 -2
- package/core/peerpay/outbox.ts +11 -1
- package/core/profiles/assertProfileEmpty.ts +287 -0
- package/core/profiles/discovery.ts +84 -0
- package/core/profiles/profileLabel.ts +13 -0
- package/core/profiles/profileStore.ts +265 -0
- package/core/profiles/purgeProfile.ts +76 -0
- package/core/profiles/removeProfile.ts +257 -0
- package/core/push/events.ts +52 -5
- package/core/push/identities.ts +55 -0
- package/core/push/profilePush.ts +143 -0
- package/core/push/registration.ts +362 -24
- package/core/push/types.ts +5 -1
- package/core/services/arcTokenStorage.ts +17 -2
- package/core/services/signingPermissionPolicy.ts +258 -0
- package/core/services/vault/guard.ts +55 -14
- package/core/services/vault/transfers.ts +6 -1
- package/core/services/vault/vaultStore.ts +16 -3
- package/core/stores/ConnectionStore.ts +11 -7
- package/core/toolboxConfig.ts +7 -3
- package/core/userAvatar.ts +12 -5
- package/core/walletDbRegistry.ts +73 -0
- package/package.json +1 -1
- package/ui/backupShares.ts +2 -3
- package/ui/components/pay/MessageBoxConfig.tsx +6 -5
- package/ui/components/ui/PencilEditField.tsx +5 -2
- package/ui/components/ui/PermissionSheet.tsx +15 -7
- package/ui/components/ui/protocolPrompt.ts +118 -0
- package/ui/components/wallet/Balance.tsx +3 -1
- package/ui/components/wallet/ProfileButton.tsx +92 -18
- package/ui/components/wallet/ProfileSwitcherPopover.tsx +247 -0
- package/ui/hooks/useOfflineNoticeActions.ts +2 -1
- package/ui/hooks/useSpendableBalance.ts +3 -1
- package/ui/printRecoveryShares.ts +6 -7
- package/ui/screens/PairScreen.tsx +2 -1
- package/ui/screens/ProfileScreen.tsx +195 -4
- package/ui/screens/SettingsScreen.tsx +8 -4
- package/ui/screens/VaultScreen.tsx +31 -2
- package/ui/screens/VaultTransferScreen.tsx +25 -2
- package/ui/screens/WalletCheckScreen.tsx +2 -1
- package/ui/screens/WalletConfigScreen.tsx +51 -21
- package/ui/screens/WalletHomeScreen.tsx +6 -3
- package/ui/tokenSeen.ts +13 -9
package/core/mnemonicWallet.ts
CHANGED
|
@@ -10,57 +10,62 @@ export interface MnemonicWalletConfig {
|
|
|
10
10
|
mnemonic?: string // Optional: provide existing mnemonic
|
|
11
11
|
passphrase?: string // Optional BIP39 passphrase
|
|
12
12
|
language?: 'en' | 'es' | 'fr' | 'it' | 'ja' | 'ko' | 'zh_CN' | 'zh_TW' // Default: 'en'
|
|
13
|
+
/** Which wallet profile to derive. Default 0. See profilePaths. */
|
|
14
|
+
profileIndex?: number
|
|
13
15
|
}
|
|
14
16
|
|
|
15
|
-
export interface
|
|
17
|
+
export interface ProfileKeys {
|
|
18
|
+
privilegedKey: PrivateKey // Derived key at m/1'/n' for the privileged key manager
|
|
19
|
+
primaryKey: number[] // Derived key at m/0'/n' for wallet
|
|
20
|
+
identityKey: string // Public key hex of the primary key
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface MnemonicWalletResult extends ProfileKeys {
|
|
16
24
|
mnemonic: string
|
|
17
|
-
rootKey: PrivateKey
|
|
18
|
-
primaryKey: number[] // Derived key at m/0'/0' for wallet
|
|
19
|
-
identityKey: string // Public key hex
|
|
20
25
|
}
|
|
21
26
|
|
|
22
27
|
/**
|
|
23
|
-
*
|
|
28
|
+
* The two hardened paths profile `n` derives from the shared seed. Every profile
|
|
29
|
+
* is a separate wallet (its own identity, storage, backup account) yet one
|
|
30
|
+
* mnemonic backs them all up. The privileged key sits on its own branch so no
|
|
31
|
+
* profile ever shares key material with another, and none uses the BIP32 master.
|
|
24
32
|
*/
|
|
25
|
-
export function
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
// Generate new mnemonic or use provided one
|
|
29
|
-
let mnemonicInstance: Mnemonic
|
|
30
|
-
if (config.mnemonic) {
|
|
31
|
-
// Validate and use existing mnemonic
|
|
32
|
-
mnemonicInstance = Mnemonic.fromString(config.mnemonic)
|
|
33
|
-
} else {
|
|
34
|
-
// Generate new random mnemonic (128 bits = 12 words by default)
|
|
35
|
-
mnemonicInstance = Mnemonic.fromRandom()
|
|
33
|
+
export function profilePaths(n: number): { primary: string; privileged: string } {
|
|
34
|
+
if (!Number.isInteger(n) || n < 0 || n >= 2 ** 31) {
|
|
35
|
+
throw new Error(`Invalid profile index: ${n}`)
|
|
36
36
|
}
|
|
37
|
+
return { primary: `m/0'/${n}'`, privileged: `m/1'/${n}'` }
|
|
38
|
+
}
|
|
37
39
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
const seed = mnemonicInstance.toSeed(passphrase)
|
|
43
|
-
|
|
44
|
-
// Create HD key from seed
|
|
45
|
-
const hdKey = HD.fromSeed(seed)
|
|
40
|
+
/** BIP39 seed → BIP32 root. The expensive step (PBKDF2): build once, derive many profiles. */
|
|
41
|
+
export function hdFromMnemonic(mnemonic: string, passphrase: string = ''): HD {
|
|
42
|
+
return HD.fromSeed(Mnemonic.fromString(mnemonic).toSeed(passphrase))
|
|
43
|
+
}
|
|
46
44
|
|
|
47
|
-
|
|
48
|
-
|
|
45
|
+
/** Profile `n`'s keys from an already-built root. */
|
|
46
|
+
export function deriveProfileKeys(hdKey: HD, n: number): ProfileKeys {
|
|
47
|
+
const paths = profilePaths(n)
|
|
48
|
+
const primary = hdKey.derive(paths.primary).privKey
|
|
49
|
+
return {
|
|
50
|
+
privilegedKey: hdKey.derive(paths.privileged).privKey,
|
|
51
|
+
primaryKey: primary.toArray(),
|
|
52
|
+
identityKey: primary.toPublicKey().toString()
|
|
53
|
+
}
|
|
54
|
+
}
|
|
49
55
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Generate a new mnemonic-based wallet
|
|
58
|
+
*/
|
|
59
|
+
export function generateMnemonicWallet(config: MnemonicWalletConfig = {}): MnemonicWalletResult {
|
|
60
|
+
const { passphrase = '', profileIndex = 0 } = config
|
|
54
61
|
|
|
55
|
-
//
|
|
56
|
-
|
|
62
|
+
// Validate and use the provided mnemonic, or generate a new random one
|
|
63
|
+
// (128 bits = 12 words by default)
|
|
64
|
+
const mnemonicInstance = config.mnemonic ? Mnemonic.fromString(config.mnemonic) : Mnemonic.fromRandom()
|
|
65
|
+
const mnemonicString = mnemonicInstance.toString()
|
|
66
|
+
const hdKey = HD.fromSeed(mnemonicInstance.toSeed(passphrase))
|
|
57
67
|
|
|
58
|
-
return {
|
|
59
|
-
mnemonic: mnemonicString,
|
|
60
|
-
rootKey,
|
|
61
|
-
primaryKey,
|
|
62
|
-
identityKey
|
|
63
|
-
}
|
|
68
|
+
return { mnemonic: mnemonicString, ...deriveProfileKeys(hdKey, profileIndex) }
|
|
64
69
|
}
|
|
65
70
|
|
|
66
71
|
/**
|
|
@@ -68,9 +73,10 @@ export function generateMnemonicWallet(config: MnemonicWalletConfig = {}): Mnemo
|
|
|
68
73
|
*/
|
|
69
74
|
export function recoverMnemonicWallet(
|
|
70
75
|
mnemonic: string,
|
|
71
|
-
passphrase: string = ''
|
|
76
|
+
passphrase: string = '',
|
|
77
|
+
profileIndex: number = 0
|
|
72
78
|
): MnemonicWalletResult {
|
|
73
|
-
return generateMnemonicWallet({ mnemonic, passphrase })
|
|
79
|
+
return generateMnemonicWallet({ mnemonic, passphrase, profileIndex })
|
|
74
80
|
}
|
|
75
81
|
|
|
76
82
|
/**
|
|
@@ -47,6 +47,8 @@ export class MonitorSupervisor {
|
|
|
47
47
|
restarts = 0
|
|
48
48
|
private generation = 0
|
|
49
49
|
private monitor: Monitor | undefined
|
|
50
|
+
/** Resolvers for inter-pass sleeps in progress, so `stop` can cut them short. */
|
|
51
|
+
private readonly sleeping = new Set<() => void>()
|
|
50
52
|
|
|
51
53
|
constructor(
|
|
52
54
|
private readonly now: () => number = () => Date.now(),
|
|
@@ -78,6 +80,25 @@ export class MonitorSupervisor {
|
|
|
78
80
|
this.lastPassAt = this.now()
|
|
79
81
|
}
|
|
80
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Stop the loop and wake it if it is sleeping between passes, so a drain
|
|
85
|
+
* (stopMonitorAndDrain) waits only for a pass actually in flight — not the
|
|
86
|
+
* rest of the inter-pass interval. The toolbox's own `stopTasks()` only clears
|
|
87
|
+
* the flag the loop checks AFTER its sleep, which left every teardown (rebuild,
|
|
88
|
+
* network or profile switch, logout) waiting up to `taskRunWaitMsecs` for
|
|
89
|
+
* nothing.
|
|
90
|
+
*/
|
|
91
|
+
stop(): void {
|
|
92
|
+
this.monitor?.stopTasks()
|
|
93
|
+
this.wake()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Cut short any inter-pass sleep. A loop whose monitor is still running just
|
|
97
|
+
* starts its next pass early; a stopped one exits and resolves its drain. */
|
|
98
|
+
wake(): void {
|
|
99
|
+
for (const wake of [...this.sleeping]) wake()
|
|
100
|
+
}
|
|
101
|
+
|
|
81
102
|
isStalled(stallMs: number = MONITOR_STALL_MS): boolean {
|
|
82
103
|
const state = this.monitor as unknown as LoopState | undefined
|
|
83
104
|
if (!state?._tasksRunning) return false
|
|
@@ -98,6 +119,18 @@ export class MonitorSupervisor {
|
|
|
98
119
|
return true
|
|
99
120
|
}
|
|
100
121
|
|
|
122
|
+
/** `wait`, but `stop` can end it early. */
|
|
123
|
+
private sleep(ms: number): Promise<void> {
|
|
124
|
+
return new Promise<void>(resolve => {
|
|
125
|
+
const wake = () => {
|
|
126
|
+
this.sleeping.delete(wake)
|
|
127
|
+
resolve()
|
|
128
|
+
}
|
|
129
|
+
this.sleeping.add(wake)
|
|
130
|
+
void this.wait(ms).then(wake, wake)
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
101
134
|
private async loop(state: LoopState, generation: number): Promise<void> {
|
|
102
135
|
while (state._tasksRunning && generation === this.generation) {
|
|
103
136
|
try {
|
|
@@ -109,7 +142,8 @@ export class MonitorSupervisor {
|
|
|
109
142
|
}
|
|
110
143
|
if (generation !== this.generation) return
|
|
111
144
|
this.lastPassAt = this.now()
|
|
112
|
-
|
|
145
|
+
if (!state._tasksRunning) break
|
|
146
|
+
await this.sleep(state.options.taskRunWaitMsecs)
|
|
113
147
|
}
|
|
114
148
|
// Only the live generation may report completion: an abandoned one waking
|
|
115
149
|
// up late must not resolve a drain that belongs to its successor.
|
|
@@ -18,6 +18,30 @@ export interface CreditInboxTaskResult {
|
|
|
18
18
|
accepted: number
|
|
19
19
|
attention: number
|
|
20
20
|
pending?: boolean
|
|
21
|
+
/**
|
|
22
|
+
* Part of the pass could not run at all (the token box could not be read). What
|
|
23
|
+
* is waiting there is unknown rather than absent: the monitor retries it as
|
|
24
|
+
* `pending`, and the profile removal refuses to read it as an empty inbox.
|
|
25
|
+
*/
|
|
26
|
+
incomplete?: boolean
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The satoshi inbox's pass and the token inbox's drain as one result. A token
|
|
31
|
+
* message that failed to credit, or a token box that could not be read, is work
|
|
32
|
+
* left in the inbox: `pending`, so the monitor tries again and the removal check
|
|
33
|
+
* does not take the inbox for empty.
|
|
34
|
+
*/
|
|
35
|
+
export function mergeInboxResults(
|
|
36
|
+
satoshis: { accepted: number; attentionCount: number; pending: boolean },
|
|
37
|
+
tokens: { credited: number; failed: number; incomplete?: boolean }
|
|
38
|
+
): CreditInboxTaskResult {
|
|
39
|
+
return {
|
|
40
|
+
accepted: satoshis.accepted + tokens.credited,
|
|
41
|
+
attention: satoshis.attentionCount,
|
|
42
|
+
pending: satoshis.pending || tokens.failed > 0 || tokens.incomplete === true,
|
|
43
|
+
...(tokens.incomplete ? { incomplete: true } : {})
|
|
44
|
+
}
|
|
21
45
|
}
|
|
22
46
|
|
|
23
47
|
export class TaskCreditInbox extends WalletMonitorTask {
|
package/core/pay/rails/handle.ts
CHANGED
|
@@ -711,13 +711,15 @@ export async function sendTokenViaHandle(args: {
|
|
|
711
711
|
*/
|
|
712
712
|
export async function drainMandalaInbox(
|
|
713
713
|
runtime: HandleTokenRuntime | undefined
|
|
714
|
-
): Promise<{ credited: number; failed: number }> {
|
|
714
|
+
): Promise<{ credited: number; failed: number; incomplete?: true }> {
|
|
715
715
|
if (!runtime?.available) return { credited: 0, failed: 0 }
|
|
716
716
|
try {
|
|
717
717
|
return await runtime.receiveFromInbox()
|
|
718
718
|
} catch (e) {
|
|
719
719
|
console.warn('[mandala] the token inbox drain failed:', e instanceof Error ? e.message : String(e))
|
|
720
|
-
|
|
720
|
+
// Not `{ 0, 0 }` alone: that reads as an inbox with nothing in it, and a
|
|
721
|
+
// caller that must know (the profile removal) has to be able to tell.
|
|
722
|
+
return { credited: 0, failed: 0, incomplete: true }
|
|
721
723
|
}
|
|
722
724
|
}
|
|
723
725
|
|
package/core/peerpay/outbox.ts
CHANGED
|
@@ -108,7 +108,7 @@ function withOutboxLock<T>(storage: StorageLike, fn: () => Promise<T>): Promise<
|
|
|
108
108
|
return run
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
-
async function readEntries(storage: StorageLike): Promise<OutboxEntry[]> {
|
|
111
|
+
async function readEntries(storage: Pick<StorageLike, 'getKeyValue'>): Promise<OutboxEntry[]> {
|
|
112
112
|
// Mutations must fail closed: treating an unreadable queue as empty would
|
|
113
113
|
// erase persisted tokens when the subsequent write succeeds.
|
|
114
114
|
const raw = await storage.getKeyValue(OUTBOX_KEY)
|
|
@@ -136,6 +136,16 @@ export async function getOutboxEntries(storage: StorageLike): Promise<OutboxEntr
|
|
|
136
136
|
}
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
/**
|
|
140
|
+
* Every outbox entry, or a throw when the queue cannot be read.
|
|
141
|
+
*
|
|
142
|
+
* For a caller that must not mistake "could not read" for "nothing owed" —
|
|
143
|
+
* removing a profile deletes the database this queue lives in.
|
|
144
|
+
*/
|
|
145
|
+
export async function getOutboxEntriesStrict(storage: Pick<StorageLike, 'getKeyValue'>): Promise<OutboxEntry[]> {
|
|
146
|
+
return readEntries(storage)
|
|
147
|
+
}
|
|
148
|
+
|
|
139
149
|
/**
|
|
140
150
|
* Persist a new outbound payment token to the outbox before delivery is attempted.
|
|
141
151
|
* Returns the generated entry ID.
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The proof that a profile holds nothing, which is what makes removing it safe.
|
|
3
|
+
*
|
|
4
|
+
* Removing a profile deletes its databases and stops monitoring it. The seed
|
|
5
|
+
* still derives the same keys, so nothing on chain is destroyed — but a coin,
|
|
6
|
+
* a half-sent payment or a payment not yet credited that lives only in that
|
|
7
|
+
* database would no longer be looked after by anything. So this answers one
|
|
8
|
+
* question, and answers it strictly: is there anything here a person could be
|
|
9
|
+
* owed, or owe?
|
|
10
|
+
*
|
|
11
|
+
* It runs on the OPEN storage of the profile being removed, and it fails
|
|
12
|
+
* closed. A check that threw says nothing about what is in the database, so
|
|
13
|
+
* every error becomes `check-failed` and never `ok`; the one way to get `ok`
|
|
14
|
+
* is for every check to have run and found nothing.
|
|
15
|
+
*
|
|
16
|
+
* The state lists are written the other way round from the spec's prose — as
|
|
17
|
+
* what is TERMINAL, with everything else blocking. For every status that exists
|
|
18
|
+
* today that is the same set, and a status added later blocks removal until
|
|
19
|
+
* somebody decides it should not, which is the safe direction to be wrong in.
|
|
20
|
+
*
|
|
21
|
+
* Read-only. The localpay queue in particular is read raw rather than through
|
|
22
|
+
* `getUnprocessed`: that reader repairs a corrupt queue as a side effect, and a
|
|
23
|
+
* check that cleaned up its own evidence would pass the second time it ran.
|
|
24
|
+
*/
|
|
25
|
+
import type { BindValue } from '../storage/methods/offlineActions'
|
|
26
|
+
import { PENDING_JOURNAL_KEY } from '../identity/handleRegistry/registration'
|
|
27
|
+
import { PENDING_KEY } from '../localpay/pending'
|
|
28
|
+
import { getOutboxEntriesStrict, unsentEntries } from '../peerpay/outbox'
|
|
29
|
+
|
|
30
|
+
/** Why a profile cannot be removed. One code per thing found, for the UI to explain. */
|
|
31
|
+
export type RemovalBlocker =
|
|
32
|
+
/** A spendable output in any basket, tokens included. */
|
|
33
|
+
| 'spendable-outputs'
|
|
34
|
+
/** A transaction that is not yet completed or failed. */
|
|
35
|
+
| 'pending-transactions'
|
|
36
|
+
/** A payment queued, being posted, parked or held for review. */
|
|
37
|
+
| 'offline-queue'
|
|
38
|
+
/** A token payment that has not reached a final state. */
|
|
39
|
+
| 'token-settlements'
|
|
40
|
+
/** A token balance, or tokens still settling. */
|
|
41
|
+
| 'token-balance'
|
|
42
|
+
/** A received payment waiting to be credited — stuck or corrupt ones included. */
|
|
43
|
+
| 'localpay-pending'
|
|
44
|
+
/** A payment sent but not yet delivered to its recipient. */
|
|
45
|
+
| 'peerpay-outbox'
|
|
46
|
+
/** A handle write that was started and not finished. */
|
|
47
|
+
| 'handle-journal'
|
|
48
|
+
/** A payment in the MessageBox inbox that the credit pass could not finish. */
|
|
49
|
+
| 'inbox-pending'
|
|
50
|
+
/**
|
|
51
|
+
* Money or unfinished business in this profile's database for ANOTHER network
|
|
52
|
+
* (or an older file of it). Removal deletes every network's database, and only
|
|
53
|
+
* the open one was looked into by name.
|
|
54
|
+
*/
|
|
55
|
+
| 'other-network'
|
|
56
|
+
/** Something could not be read, so nothing can be said. */
|
|
57
|
+
| 'check-failed'
|
|
58
|
+
|
|
59
|
+
export type ProfileEmptyResult = { ok: true } | { ok: false; reasons: RemovalBlocker[] }
|
|
60
|
+
|
|
61
|
+
/** The slice of `SQLiteDatabase` the checks need. */
|
|
62
|
+
export interface ProfileEmptyDb {
|
|
63
|
+
getFirstAsync(sql: string, params: BindValue[]): Promise<unknown>
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Structurally satisfied by `StorageExpoSQLite`. `sqliteDb` is `undefined` once
|
|
68
|
+
* the storage has been destroyed, and that reads as `check-failed`.
|
|
69
|
+
*/
|
|
70
|
+
export interface ProfileEmptyStorage {
|
|
71
|
+
readonly sqliteDb: ProfileEmptyDb | undefined
|
|
72
|
+
getKeyValue(key: string): Promise<string | undefined>
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface AssertProfileEmptyDeps {
|
|
76
|
+
/**
|
|
77
|
+
* One forced pass over the MessageBox inbox, resolving when it has run to the
|
|
78
|
+
* end. It runs FIRST, so whatever it credits is already in the database when
|
|
79
|
+
* the checks below read it.
|
|
80
|
+
*
|
|
81
|
+
* `pending` is a payment still waiting to be credited; `attention` is one the
|
|
82
|
+
* pass gave up on or could not parse. Either is money this device was told
|
|
83
|
+
* about and does not hold yet. A pass that cannot run at all (offline, the
|
|
84
|
+
* box unreachable) rejects, and that is `check-failed`: an unread inbox is
|
|
85
|
+
* not an empty one. A wallet with no MessageBox host has nothing to drain and
|
|
86
|
+
* resolves `{ attention: 0, pending: false }`.
|
|
87
|
+
*/
|
|
88
|
+
creditInbox: () => Promise<{ attention: number; pending: boolean }>
|
|
89
|
+
/**
|
|
90
|
+
* The Mandala runtime's `balances()`, when this wallet has one. Belt and
|
|
91
|
+
* braces only: the runtime's own token listing swallows its errors into an
|
|
92
|
+
* empty list, so a zero here proves less than it appears to. The SQL checks
|
|
93
|
+
* on outputs and settlements are what actually cover tokens, which is why
|
|
94
|
+
* this may be left out.
|
|
95
|
+
*/
|
|
96
|
+
mandalaBalances?: () => Promise<ReadonlyArray<{ baseUnits: number; unsettledBaseUnits: number }>>
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Terminal lists, not blocking lists — see the header.
|
|
100
|
+
const SPENDABLE_OUTPUTS = 'SELECT 1 AS found FROM outputs WHERE userId = ? AND spendable <> 0 LIMIT 1'
|
|
101
|
+
const OPEN_TRANSACTIONS =
|
|
102
|
+
"SELECT 1 AS found FROM transactions WHERE userId = ? AND status NOT IN ('completed', 'failed') LIMIT 1"
|
|
103
|
+
// Equal to queued/posting/parked/import_hold for every status there is.
|
|
104
|
+
const OPEN_OFFLINE_ACTIONS =
|
|
105
|
+
"SELECT 1 AS found FROM offline_actions WHERE userId = ? AND status NOT IN ('sent', 'rejected', 'acknowledged') LIMIT 1"
|
|
106
|
+
// No userId column: this table is one database's worth, and a database is one profile's.
|
|
107
|
+
const OPEN_SETTLEMENTS =
|
|
108
|
+
"SELECT 1 AS found FROM token_settlements WHERE state NOT IN ('broadcast', 'admitted', 'refused', 'orphaned') LIMIT 1"
|
|
109
|
+
// A corrupt localpay queue is copied here and the live key reset (pending.ts `readAll`).
|
|
110
|
+
const QUARANTINED_PENDING =
|
|
111
|
+
"SELECT 1 AS found FROM key_value_store WHERE key LIKE 'localpay\\_pending\\_corrupt\\_%' ESCAPE '\\' LIMIT 1"
|
|
112
|
+
|
|
113
|
+
async function exists(db: ProfileEmptyDb | undefined, sql: string, params: BindValue[]): Promise<boolean> {
|
|
114
|
+
if (!db) throw new Error('assertProfileEmpty: the database is closed')
|
|
115
|
+
return (await db.getFirstAsync(sql, params)) != null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Any entry that is not finished, or a queue that cannot be understood. */
|
|
119
|
+
async function receivedPaymentsWaiting(storage: ProfileEmptyStorage): Promise<boolean> {
|
|
120
|
+
const raw = await storage.getKeyValue(PENDING_KEY)
|
|
121
|
+
if (raw) {
|
|
122
|
+
let parsed: unknown
|
|
123
|
+
try {
|
|
124
|
+
parsed = JSON.parse(raw)
|
|
125
|
+
} catch {
|
|
126
|
+
return true
|
|
127
|
+
}
|
|
128
|
+
if (!Array.isArray(parsed)) return true
|
|
129
|
+
// `completed` entries are credited already, so what they were worth is in
|
|
130
|
+
// `outputs`; the queue drops them on its next write anyway.
|
|
131
|
+
if (parsed.some(entry => (entry as { status?: unknown } | null)?.status !== 'completed')) return true
|
|
132
|
+
}
|
|
133
|
+
return await exists(storage.sqliteDb, QUARANTINED_PENDING, [])
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function assertProfileEmpty(
|
|
137
|
+
storage: ProfileEmptyStorage,
|
|
138
|
+
userId: number,
|
|
139
|
+
deps: AssertProfileEmptyDeps
|
|
140
|
+
): Promise<ProfileEmptyResult> {
|
|
141
|
+
// Bound into every query below: anything but a real row id would match
|
|
142
|
+
// nothing, and "matched nothing" is the answer this function must never give
|
|
143
|
+
// for a reason other than the profile being empty.
|
|
144
|
+
if (!Number.isInteger(userId) || userId <= 0) return { ok: false, reasons: ['check-failed'] }
|
|
145
|
+
|
|
146
|
+
const reasons: RemovalBlocker[] = []
|
|
147
|
+
const note = (reason: RemovalBlocker) => {
|
|
148
|
+
if (!reasons.includes(reason)) reasons.push(reason)
|
|
149
|
+
}
|
|
150
|
+
/** Every check runs even after one has failed, so the user is told all of it. */
|
|
151
|
+
const check = async (blocker: RemovalBlocker, blocked: () => Promise<boolean>) => {
|
|
152
|
+
try {
|
|
153
|
+
if (await blocked()) note(blocker)
|
|
154
|
+
} catch {
|
|
155
|
+
note('check-failed')
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const db = storage.sqliteDb
|
|
160
|
+
|
|
161
|
+
await check('inbox-pending', async () => {
|
|
162
|
+
const pass = await deps.creditInbox()
|
|
163
|
+
return !(pass.pending === false && pass.attention === 0)
|
|
164
|
+
})
|
|
165
|
+
await check('spendable-outputs', () => exists(db, SPENDABLE_OUTPUTS, [userId]))
|
|
166
|
+
await check('pending-transactions', () => exists(db, OPEN_TRANSACTIONS, [userId]))
|
|
167
|
+
await check('offline-queue', () => exists(db, OPEN_OFFLINE_ACTIONS, [userId]))
|
|
168
|
+
await check('token-settlements', () => exists(db, OPEN_SETTLEMENTS, []))
|
|
169
|
+
await check('token-balance', async () => {
|
|
170
|
+
if (!deps.mandalaBalances) return false
|
|
171
|
+
const balances = await deps.mandalaBalances()
|
|
172
|
+
return balances.some(b => !(b.baseUnits === 0 && b.unsettledBaseUnits === 0))
|
|
173
|
+
})
|
|
174
|
+
await check('localpay-pending', () => receivedPaymentsWaiting(storage))
|
|
175
|
+
await check('peerpay-outbox', async () => unsentEntries(await getOutboxEntriesStrict(storage)).length > 0)
|
|
176
|
+
// Any value at all, not one parsed: `clearJournal` leaves `''` behind, and
|
|
177
|
+
// that is the only thing that means "nothing in flight".
|
|
178
|
+
await check('handle-journal', async () => !!(await storage.getKeyValue(PENDING_JOURNAL_KEY)))
|
|
179
|
+
|
|
180
|
+
return reasons.length === 0 ? { ok: true } : { ok: false, reasons }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Every blocker found by any of `results`, once each, in the order they were found. `ok` only when all are. */
|
|
184
|
+
export function combineEmpty(...results: ProfileEmptyResult[]): ProfileEmptyResult {
|
|
185
|
+
const reasons: RemovalBlocker[] = []
|
|
186
|
+
for (const result of results) {
|
|
187
|
+
if (result.ok) continue
|
|
188
|
+
for (const reason of result.reasons) if (!reasons.includes(reason)) reasons.push(reason)
|
|
189
|
+
}
|
|
190
|
+
return reasons.length === 0 ? { ok: true } : { ok: false, reasons }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** A wallet database opened only to be read. The slice of `SQLiteDatabase` the checks use. */
|
|
194
|
+
export interface ClosedProfileDb extends ProfileEmptyDb {
|
|
195
|
+
closeAsync(): Promise<void>
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export interface DatabasesEmptyDeps {
|
|
199
|
+
/** Every database file to look into: all those registered for the identity, minus any already checked. Rejects when the registry cannot be read. */
|
|
200
|
+
list(): Promise<readonly string[]>
|
|
201
|
+
/** Open one of them. Opening a file that is gone creates it empty, which reads as a database with nothing in it. */
|
|
202
|
+
open(filename: string): Promise<ClosedProfileDb>
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const HAS_USERS_TABLE = "SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = 'users' LIMIT 1"
|
|
206
|
+
const USER_BY_IDENTITY = 'SELECT userId FROM users WHERE identityKey = ? LIMIT 1'
|
|
207
|
+
|
|
208
|
+
/** One file: every check but the inbox (which belongs to a wallet that is open, and none of these is). */
|
|
209
|
+
async function databaseEmpty(db: ClosedProfileDb, identityKey: string): Promise<ProfileEmptyResult> {
|
|
210
|
+
// No `users` table: a file that was never migrated, such as a registry entry
|
|
211
|
+
// whose file was gone and has just been created empty by opening it. Read from
|
|
212
|
+
// sqlite_master, so a database that could not be read at all still throws.
|
|
213
|
+
if (!(await exists(db, HAS_USERS_TABLE, []))) return { ok: true }
|
|
214
|
+
const row = (await db.getFirstAsync(USER_BY_IDENTITY, [identityKey])) as { userId?: unknown } | null
|
|
215
|
+
// Nothing in this file was ever written for this identity.
|
|
216
|
+
if (!row) return { ok: true }
|
|
217
|
+
const userId = Number(row.userId)
|
|
218
|
+
return assertProfileEmpty(
|
|
219
|
+
{
|
|
220
|
+
sqliteDb: db,
|
|
221
|
+
getKeyValue: async key =>
|
|
222
|
+
(
|
|
223
|
+
(await db.getFirstAsync('SELECT value FROM key_value_store WHERE key = ?', [key])) as {
|
|
224
|
+
value?: string
|
|
225
|
+
} | null
|
|
226
|
+
)?.value
|
|
227
|
+
},
|
|
228
|
+
userId,
|
|
229
|
+
// The MessageBox inbox is read through an open wallet, and none of these is one.
|
|
230
|
+
// What is waiting there stays on the server until a wallet for the identity reads it.
|
|
231
|
+
{ creditInbox: async () => ({ attention: 0, pending: false }) }
|
|
232
|
+
)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Look into every database file `deps.list()` names for the same things
|
|
237
|
+
* `assertProfileEmpty` checks in the open one, each file on its own connection,
|
|
238
|
+
* closed again afterwards. Fails closed: a registry that cannot be read, a file
|
|
239
|
+
* that cannot be opened and any read that throws are all `check-failed`.
|
|
240
|
+
*
|
|
241
|
+
* Removal deletes a profile's databases on EVERY network, while the open
|
|
242
|
+
* storage proves one of them empty; this is what covers the rest, before the
|
|
243
|
+
* delete and again once the profile's own wallet is down.
|
|
244
|
+
*/
|
|
245
|
+
export async function assertDatabasesEmpty(identityKey: string, deps: DatabasesEmptyDeps): Promise<ProfileEmptyResult> {
|
|
246
|
+
let files: readonly string[]
|
|
247
|
+
try {
|
|
248
|
+
files = await deps.list()
|
|
249
|
+
} catch {
|
|
250
|
+
return { ok: false, reasons: ['check-failed'] }
|
|
251
|
+
}
|
|
252
|
+
const results: ProfileEmptyResult[] = []
|
|
253
|
+
for (const filename of files) {
|
|
254
|
+
let db: ClosedProfileDb | undefined
|
|
255
|
+
try {
|
|
256
|
+
db = await deps.open(filename)
|
|
257
|
+
results.push(await databaseEmpty(db, identityKey))
|
|
258
|
+
} catch {
|
|
259
|
+
results.push({ ok: false, reasons: ['check-failed'] })
|
|
260
|
+
} finally {
|
|
261
|
+
try {
|
|
262
|
+
await db?.closeAsync()
|
|
263
|
+
} catch {
|
|
264
|
+
// A handle that will not close says nothing about what was in it.
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return combineEmpty(...results)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* `assertDatabasesEmpty` for the files of the networks that are NOT open. What it
|
|
273
|
+
* finds there is reported as `other-network`, since the person looking at an empty
|
|
274
|
+
* balance on the network they are on needs to be told where the rest is — every
|
|
275
|
+
* reason but `check-failed`, which stays what it is.
|
|
276
|
+
*/
|
|
277
|
+
export async function assertOtherNetworksEmpty(
|
|
278
|
+
identityKey: string,
|
|
279
|
+
deps: DatabasesEmptyDeps
|
|
280
|
+
): Promise<ProfileEmptyResult> {
|
|
281
|
+
const result = await assertDatabasesEmpty(identityKey, deps)
|
|
282
|
+
if (result.ok) return result
|
|
283
|
+
return combineEmpty({
|
|
284
|
+
ok: false,
|
|
285
|
+
reasons: result.reasons.map<RemovalBlocker>(reason => (reason === 'check-failed' ? reason : 'other-network'))
|
|
286
|
+
})
|
|
287
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Restore discovery: after a seed is imported, find the other profiles it backed up.
|
|
3
|
+
*
|
|
4
|
+
* The mnemonic says nothing about how many profiles were ever used, but each one
|
|
5
|
+
* pushed its history to its own remote-backup account (the pseudonym derives from
|
|
6
|
+
* that profile's primary key). So probe profile 1, 2, … in turn: a profile with a
|
|
7
|
+
* backup on any network exists; the first index with none on every network ends
|
|
8
|
+
* the search. Found profiles are only registered here — each replays its backup
|
|
9
|
+
* the first time the user switches to it, so an import never stalls on them.
|
|
10
|
+
*
|
|
11
|
+
* A profile removed on this device keeps its slot as a tombstone. Discovery
|
|
12
|
+
* leaves it exactly as it is: no probe, no registration, and it does not end the
|
|
13
|
+
* search, so the profiles after it are still found.
|
|
14
|
+
*
|
|
15
|
+
* Known gap: a profile that never backed anything up (unused, or backup turned
|
|
16
|
+
* off) stops the search, hiding any profile after it. Adding a profile again
|
|
17
|
+
* restores whatever exists at the next index.
|
|
18
|
+
*/
|
|
19
|
+
import type { AppChain } from '../config'
|
|
20
|
+
import { BACKUP_CHAINS, type BackupChain } from '../backup/constants'
|
|
21
|
+
import { listBackups } from '../backup/restore'
|
|
22
|
+
import { deriveProfileKeys, hdFromMnemonic } from '../mnemonicWallet'
|
|
23
|
+
import { appendProfile, getProfilesState } from './profileStore'
|
|
24
|
+
|
|
25
|
+
/** Whether `primaryKey` has a remote backup on `chain`. May throw on a network error. */
|
|
26
|
+
export type ProfileProbe = (primaryKey: number[], chain: BackupChain) => Promise<boolean>
|
|
27
|
+
|
|
28
|
+
export interface DiscoverProfilesDeps {
|
|
29
|
+
mnemonic: string
|
|
30
|
+
probe: ProfileProbe
|
|
31
|
+
/** Record profile `index` as existing on `network`. Called in index order. */
|
|
32
|
+
register: (index: number, network: AppChain) => Promise<void>
|
|
33
|
+
/** Indices to pass over (profiles removed on this device): not probed, not registered, not a stop. */
|
|
34
|
+
skip?: (index: number) => boolean
|
|
35
|
+
/** First index to probe. Default 1 — profile 0 is the wallet being imported. */
|
|
36
|
+
startIndex?: number
|
|
37
|
+
/** Hard stop on the number of profiles probed. Default 50. */
|
|
38
|
+
maxProfiles?: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Probe profiles from `startIndex` until the first one with no backup; returns how many were registered. */
|
|
42
|
+
export async function discoverProfiles(deps: DiscoverProfilesDeps): Promise<number> {
|
|
43
|
+
const start = deps.startIndex ?? 1
|
|
44
|
+
const max = deps.maxProfiles ?? 50
|
|
45
|
+
// One PBKDF2 for the whole search; every profile derives from the same root.
|
|
46
|
+
const hd = hdFromMnemonic(deps.mnemonic)
|
|
47
|
+
let registered = 0
|
|
48
|
+
for (let n = start; n < start + max; n++) {
|
|
49
|
+
if (deps.skip?.(n)) continue
|
|
50
|
+
const { primaryKey } = deriveProfileKeys(hd, n)
|
|
51
|
+
const found: BackupChain[] = []
|
|
52
|
+
try {
|
|
53
|
+
for (const chain of BACKUP_CHAINS) {
|
|
54
|
+
if (await deps.probe(primaryKey, chain)) found.push(chain)
|
|
55
|
+
}
|
|
56
|
+
} catch (err) {
|
|
57
|
+
// An outage is not evidence the profile is absent: stop without guessing,
|
|
58
|
+
// keeping what was already found. Add profile recovers the rest later.
|
|
59
|
+
console.warn(`[profiles] discovery stopped at profile ${n}:`, err)
|
|
60
|
+
break
|
|
61
|
+
}
|
|
62
|
+
if (found.length === 0) break
|
|
63
|
+
await deps.register(n, found.includes('main') ? 'main' : found[0])
|
|
64
|
+
registered++
|
|
65
|
+
}
|
|
66
|
+
return registered
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Add a discovered profile to the store, awaiting its first restore. Idempotent:
|
|
71
|
+
* only the next free slot is appended, so an index the store already holds (live
|
|
72
|
+
* or removed) is left untouched and a second import of the same seed adds
|
|
73
|
+
* nothing. Slots are counted with tombstones, never without them.
|
|
74
|
+
*/
|
|
75
|
+
export async function registerDiscoveredProfile(index: number, network: AppChain): Promise<void> {
|
|
76
|
+
if (index === getProfilesState().profiles.length) {
|
|
77
|
+
await appendProfile(network, { needsRestore: true })
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The production probe: a non-empty backup manifest on the backup server. */
|
|
82
|
+
export function backupProbe(baseUrl: string): ProfileProbe {
|
|
83
|
+
return async (primaryKey, chain) => (await listBackups({ primaryKey, chain, baseUrl })).length > 0
|
|
84
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ProfileRecord } from './profileStore'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the user calls a profile: the private name they gave it, else the
|
|
5
|
+
* default `profile<n+1>`. The number follows the derivation index, so removing
|
|
6
|
+
* a profile never renumbers the ones after it.
|
|
7
|
+
*/
|
|
8
|
+
export function profileLabel(
|
|
9
|
+
record: Pick<ProfileRecord, 'index' | 'name'>,
|
|
10
|
+
t: (key: string, options?: Record<string, unknown>) => string
|
|
11
|
+
): string {
|
|
12
|
+
return record.name || t('profile_label', { number: record.index + 1 })
|
|
13
|
+
}
|