@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
package/core/logging.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
let lastLogTime = performance.now()
|
|
2
|
+
|
|
3
|
+
// Detect truecolor support
|
|
4
|
+
const supportsTruecolor = process.env.COLORTERM === 'truecolor'
|
|
5
|
+
|
|
6
|
+
// Import logging configuration with error handling
|
|
7
|
+
let loggingConfig: { [file: string]: boolean } = { default: true }
|
|
8
|
+
try {
|
|
9
|
+
loggingConfig = require('./logging.config').default || { default: true }
|
|
10
|
+
} catch (e) {
|
|
11
|
+
console.warn('Failed to load logging.config.ts, using default settings:', e)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Master runtime kill-switch for ALL app logging. Defaults to __DEV__ (on in
|
|
15
|
+
// dev, silent in production). The dev menu / a JS debugger can flip this at
|
|
16
|
+
// runtime to silence the console.log flood that blocks the JS thread while
|
|
17
|
+
// reproducing a slow interaction — see utils/devMenu.ts.
|
|
18
|
+
let loggingEnabled = typeof __DEV__ !== 'undefined' ? __DEV__ : true
|
|
19
|
+
// Whether to relay logs emitted INSIDE WebView pages onto the RN JS thread.
|
|
20
|
+
// Off by default: a chatty page can otherwise flood the bridge and jank the UI.
|
|
21
|
+
let forwardWebViewLogs = false
|
|
22
|
+
|
|
23
|
+
export const setLoggingEnabled = (enabled: boolean) => {
|
|
24
|
+
loggingEnabled = enabled
|
|
25
|
+
}
|
|
26
|
+
export const isLoggingEnabled = () => loggingEnabled
|
|
27
|
+
export const setForwardWebViewLogs = (enabled: boolean) => {
|
|
28
|
+
forwardWebViewLogs = enabled
|
|
29
|
+
}
|
|
30
|
+
export const shouldForwardWebViewLogs = () => forwardWebViewLogs
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Gated drop-in replacement for raw `console.log`. Use this in hot paths so the
|
|
34
|
+
* master switch (and production builds) can silence the flood. Cheap when off:
|
|
35
|
+
* returns before touching its arguments, so the cost of building log strings /
|
|
36
|
+
* serializing objects is never paid when logging is disabled.
|
|
37
|
+
*/
|
|
38
|
+
export const devLog = (...args: any[]) => {
|
|
39
|
+
if (!loggingEnabled) return
|
|
40
|
+
console.log(...args)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const colorize = (elapsed: number) => {
|
|
44
|
+
if (elapsed > 1.0) {
|
|
45
|
+
return supportsTruecolor
|
|
46
|
+
? `\x1b[38;2;255;0;0m` // red
|
|
47
|
+
: `\x1b[31m` // ANSI red
|
|
48
|
+
} else if (elapsed > 0.5) {
|
|
49
|
+
return supportsTruecolor
|
|
50
|
+
? `\x1b[38;2;255;165;0m` // orange
|
|
51
|
+
: `\x1b[33;1m` // bright yellow as orange
|
|
52
|
+
} else if (elapsed > 0.3) {
|
|
53
|
+
return supportsTruecolor
|
|
54
|
+
? `\x1b[38;2;255;255;0m` // yellow
|
|
55
|
+
: `\x1b[33m` // ANSI yellow
|
|
56
|
+
} else {
|
|
57
|
+
return `\x1b[0m` // default
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const logWithTimestamp = (file: string = 'unknown', message: string = 'No message', ...args: any[]) => {
|
|
62
|
+
// Master runtime switch first (cheapest bail-out).
|
|
63
|
+
if (!loggingEnabled) return
|
|
64
|
+
// Check if logging is enabled for this file (fall back to default if not set)
|
|
65
|
+
const isEnabled = loggingConfig[file] !== undefined ? loggingConfig[file] : loggingConfig['default']
|
|
66
|
+
if (!isEnabled) return
|
|
67
|
+
|
|
68
|
+
const now = performance.now()
|
|
69
|
+
const elapsedSec = (now - lastLogTime) / 1000
|
|
70
|
+
lastLogTime = now
|
|
71
|
+
|
|
72
|
+
const timestamp = new Date().toISOString()
|
|
73
|
+
const elapsed = elapsedSec.toFixed(3)
|
|
74
|
+
const color = colorize(elapsedSec)
|
|
75
|
+
|
|
76
|
+
console.log(`[${timestamp}] ${color}[${elapsed}s]\x1b[0m [${file}] ${message}`, ...args)
|
|
77
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mnemonic-based wallet utilities for noWAB (self-custodial) mode
|
|
3
|
+
*
|
|
4
|
+
* Uses @bsv/sdk Mnemonic and HD classes for BIP39 mnemonic and BIP32 HD key derivation
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { Mnemonic, HD, PrivateKey } from '@bsv/sdk'
|
|
8
|
+
|
|
9
|
+
export interface MnemonicWalletConfig {
|
|
10
|
+
mnemonic?: string // Optional: provide existing mnemonic
|
|
11
|
+
passphrase?: string // Optional BIP39 passphrase
|
|
12
|
+
language?: 'en' | 'es' | 'fr' | 'it' | 'ja' | 'ko' | 'zh_CN' | 'zh_TW' // Default: 'en'
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface MnemonicWalletResult {
|
|
16
|
+
mnemonic: string
|
|
17
|
+
rootKey: PrivateKey
|
|
18
|
+
primaryKey: number[] // Derived key at m/0'/0' for wallet
|
|
19
|
+
identityKey: string // Public key hex
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Generate a new mnemonic-based wallet
|
|
24
|
+
*/
|
|
25
|
+
export function generateMnemonicWallet(config: MnemonicWalletConfig = {}): MnemonicWalletResult {
|
|
26
|
+
const { passphrase = '' } = config
|
|
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()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Get mnemonic as string
|
|
39
|
+
const mnemonicString = mnemonicInstance.toString()
|
|
40
|
+
|
|
41
|
+
// Derive seed from mnemonic
|
|
42
|
+
const seed = mnemonicInstance.toSeed(passphrase)
|
|
43
|
+
|
|
44
|
+
// Create HD key from seed
|
|
45
|
+
const hdKey = HD.fromSeed(seed)
|
|
46
|
+
|
|
47
|
+
// Get root key
|
|
48
|
+
const rootKey = hdKey.privKey
|
|
49
|
+
|
|
50
|
+
// Derive primary key at path m/0'/0' (hardened derivation)
|
|
51
|
+
// This is the key used as the wallet's primary key
|
|
52
|
+
const derivedHdKey = hdKey.derive("m/0'/0'")
|
|
53
|
+
const primaryKey = derivedHdKey.privKey.toArray()
|
|
54
|
+
|
|
55
|
+
// Get identity key (public key) for the derived key
|
|
56
|
+
const identityKey = derivedHdKey.privKey.toPublicKey().toString()
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
mnemonic: mnemonicString,
|
|
60
|
+
rootKey,
|
|
61
|
+
primaryKey,
|
|
62
|
+
identityKey
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Recover wallet from existing mnemonic
|
|
68
|
+
*/
|
|
69
|
+
export function recoverMnemonicWallet(
|
|
70
|
+
mnemonic: string,
|
|
71
|
+
passphrase: string = ''
|
|
72
|
+
): MnemonicWalletResult {
|
|
73
|
+
return generateMnemonicWallet({ mnemonic, passphrase })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Validate a mnemonic phrase
|
|
78
|
+
*/
|
|
79
|
+
export function validateMnemonic(mnemonic: string): boolean {
|
|
80
|
+
try {
|
|
81
|
+
Mnemonic.fromString(mnemonic)
|
|
82
|
+
return true
|
|
83
|
+
} catch {
|
|
84
|
+
return false
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Generate a random mnemonic of specified strength
|
|
90
|
+
* @param strength Entropy bits: 128 (12 words), 160 (15 words), 192 (18 words), 224 (21 words), 256 (24 words)
|
|
91
|
+
*/
|
|
92
|
+
export function generateRandomMnemonic(strength: 128 | 160 | 192 | 224 | 256 = 128): string {
|
|
93
|
+
// For now, @bsv/sdk Mnemonic.fromRandom() generates 128 bits (12 words)
|
|
94
|
+
// If you need different strengths, you may need to generate entropy manually
|
|
95
|
+
const mnemonic = Mnemonic.fromRandom()
|
|
96
|
+
return mnemonic.toString()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Get word count for a mnemonic
|
|
101
|
+
*/
|
|
102
|
+
export function getMnemonicWordCount(mnemonic: string): number {
|
|
103
|
+
return mnemonic.trim().split(/\s+/).length
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Get expected word count for entropy bits
|
|
108
|
+
*/
|
|
109
|
+
export function getExpectedWordCount(entropyBits: number): number {
|
|
110
|
+
return Math.floor((entropyBits + entropyBits / 32) / 11)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Parse mnemonic safely and return validation result
|
|
115
|
+
*/
|
|
116
|
+
export interface MnemonicValidationResult {
|
|
117
|
+
valid: boolean
|
|
118
|
+
wordCount?: number
|
|
119
|
+
expectedWordCount?: number
|
|
120
|
+
error?: string
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function parseMnemonic(mnemonic: string): MnemonicValidationResult {
|
|
124
|
+
const trimmed = mnemonic.trim()
|
|
125
|
+
const words = trimmed.split(/\s+/)
|
|
126
|
+
const wordCount = words.length
|
|
127
|
+
|
|
128
|
+
// Valid word counts: 12, 15, 18, 21, 24
|
|
129
|
+
const validCounts = [12, 15, 18, 21, 24]
|
|
130
|
+
|
|
131
|
+
if (!validCounts.includes(wordCount)) {
|
|
132
|
+
return {
|
|
133
|
+
valid: false,
|
|
134
|
+
wordCount,
|
|
135
|
+
error: `Invalid word count: ${wordCount}. Expected: ${validCounts.join(', ')}`
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
Mnemonic.fromString(trimmed)
|
|
141
|
+
return {
|
|
142
|
+
valid: true,
|
|
143
|
+
wordCount
|
|
144
|
+
}
|
|
145
|
+
} catch (error: any) {
|
|
146
|
+
return {
|
|
147
|
+
valid: false,
|
|
148
|
+
wordCount,
|
|
149
|
+
error: error.message || 'Invalid mnemonic phrase'
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Convert mnemonic to displayable format with numbered words
|
|
156
|
+
*/
|
|
157
|
+
export function formatMnemonicForDisplay(mnemonic: string): string[] {
|
|
158
|
+
return mnemonic.trim().split(/\s+/)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Helper to securely store mnemonic (should be encrypted in production)
|
|
163
|
+
* Returns base64 encoded mnemonic
|
|
164
|
+
*/
|
|
165
|
+
export function encodeMnemonicForStorage(mnemonic: string): string {
|
|
166
|
+
// In production, this should encrypt the mnemonic
|
|
167
|
+
// For now, just base64 encode
|
|
168
|
+
return btoa(mnemonic)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Helper to retrieve stored mnemonic
|
|
173
|
+
*/
|
|
174
|
+
export function decodeMnemonicFromStorage(encoded: string): string {
|
|
175
|
+
try {
|
|
176
|
+
return atob(encoded)
|
|
177
|
+
} catch {
|
|
178
|
+
throw new Error('Failed to decode stored mnemonic')
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pushes wallet-database deltas to the encrypted backup log.
|
|
3
|
+
*
|
|
4
|
+
* Triggering mirrors TaskSendOffline: gated on the app's single online signal, with an
|
|
5
|
+
* immediate pass when something changes and exponential backoff after failures.
|
|
6
|
+
*
|
|
7
|
+
* All state is static and process-global BY DESIGN. The monitor is torn down and rebuilt on
|
|
8
|
+
* network switches and wallet rebuilds, and backup progress — particularly the backoff after
|
|
9
|
+
* a failing server — must survive that. A per-instance version would reset its backoff every
|
|
10
|
+
* rebuild and hammer a service that is down.
|
|
11
|
+
*
|
|
12
|
+
* The work itself is deliberately small. Monitor tasks run back-to-back with no yielding, so
|
|
13
|
+
* a pass takes at most one chunk and the interval floor keeps it off the JS thread the rest
|
|
14
|
+
* of the time.
|
|
15
|
+
*/
|
|
16
|
+
import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
|
|
17
|
+
import type { Monitor } from '@bsv/wallet-toolbox-mobile'
|
|
18
|
+
import { MIN_PUSH_INTERVAL_MS } from '../backup/constants'
|
|
19
|
+
import type { PushResult } from '../backup/push'
|
|
20
|
+
|
|
21
|
+
export class TaskBackupPush extends WalletMonitorTask {
|
|
22
|
+
static taskName = 'BackupPush'
|
|
23
|
+
|
|
24
|
+
static readonly BASE_BACKOFF_MS = 30_000
|
|
25
|
+
static readonly MAX_BACKOFF_MS = 900_000
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Re-check even when nothing has announced a change.
|
|
29
|
+
*
|
|
30
|
+
* `noteChanged` is wired to the paths we know about, but the wallet database can be
|
|
31
|
+
* written by paths that do not announce themselves — a dApp creating an action produces
|
|
32
|
+
* no status *transition*, so the Monitor's onTransactionStatusChanged never fires for it.
|
|
33
|
+
* Rather than depend on having found every writer, this floor guarantees the log
|
|
34
|
+
* converges: the cost of a needless check is one local getSyncChunk that returns empty.
|
|
35
|
+
*/
|
|
36
|
+
static readonly IDLE_RECHECK_MS = 300_000
|
|
37
|
+
|
|
38
|
+
/** Last observation from the app's online listener. Gates the trigger entirely. */
|
|
39
|
+
static onlineNow = false
|
|
40
|
+
/** The database may hold un-pushed changes. Set pessimistically; a clean pass clears it. */
|
|
41
|
+
static hasChanges = false
|
|
42
|
+
/** An immediate pass has been requested. Consumed at the top of runTask. */
|
|
43
|
+
static checkNow = false
|
|
44
|
+
/** Earliest time the next pass may run. */
|
|
45
|
+
static nextDueAt = 0
|
|
46
|
+
/** When the last pass started, for the idle re-check floor. */
|
|
47
|
+
static lastRunAt = 0
|
|
48
|
+
static backoffMs = TaskBackupPush.BASE_BACKOFF_MS
|
|
49
|
+
/** Last error, kept so settings can show why backups are not progressing. */
|
|
50
|
+
static lastError: string | undefined
|
|
51
|
+
/** Time of the last successful pass, for the backup-health display. */
|
|
52
|
+
static lastSuccessAt: number | undefined
|
|
53
|
+
|
|
54
|
+
static noteConnectivity (online: boolean): void {
|
|
55
|
+
TaskBackupPush.onlineNow = online
|
|
56
|
+
if (online) {
|
|
57
|
+
TaskBackupPush.checkNow = true
|
|
58
|
+
TaskBackupPush.backoffMs = TaskBackupPush.BASE_BACKOFF_MS
|
|
59
|
+
TaskBackupPush.nextDueAt = 0
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** New wallet activity. Cheap to over-call: one idle pass clears the flag. */
|
|
64
|
+
static noteChanged (): void {
|
|
65
|
+
TaskBackupPush.hasChanges = true
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** User asked for an immediate backup. */
|
|
69
|
+
static requestNow (): void {
|
|
70
|
+
TaskBackupPush.checkNow = true
|
|
71
|
+
TaskBackupPush.backoffMs = TaskBackupPush.BASE_BACKOFF_MS
|
|
72
|
+
TaskBackupPush.nextDueAt = 0
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
static noteRan (at: number): void {
|
|
76
|
+
TaskBackupPush.nextDueAt = at + MIN_PUSH_INTERVAL_MS
|
|
77
|
+
TaskBackupPush.lastRunAt = at
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
static noteFailure (at: number): void {
|
|
81
|
+
TaskBackupPush.nextDueAt = at + TaskBackupPush.backoffMs
|
|
82
|
+
TaskBackupPush.backoffMs = Math.min(
|
|
83
|
+
TaskBackupPush.backoffMs * 2,
|
|
84
|
+
TaskBackupPush.MAX_BACKOFF_MS
|
|
85
|
+
)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Test seam; also used when the user signs out. */
|
|
89
|
+
static reset (): void {
|
|
90
|
+
TaskBackupPush.onlineNow = false
|
|
91
|
+
TaskBackupPush.hasChanges = false
|
|
92
|
+
TaskBackupPush.checkNow = false
|
|
93
|
+
TaskBackupPush.nextDueAt = 0
|
|
94
|
+
TaskBackupPush.lastRunAt = 0
|
|
95
|
+
TaskBackupPush.backoffMs = TaskBackupPush.BASE_BACKOFF_MS
|
|
96
|
+
TaskBackupPush.lastError = undefined
|
|
97
|
+
TaskBackupPush.lastSuccessAt = undefined
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
constructor (
|
|
101
|
+
monitor: Monitor,
|
|
102
|
+
private readonly push: () => Promise<PushResult>
|
|
103
|
+
) {
|
|
104
|
+
super(monitor, TaskBackupPush.taskName)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
trigger (nowMsecsSinceEpoch: number): { run: boolean } {
|
|
108
|
+
if (!TaskBackupPush.onlineNow) return { run: false }
|
|
109
|
+
if (TaskBackupPush.checkNow) return { run: true }
|
|
110
|
+
if (TaskBackupPush.hasChanges) {
|
|
111
|
+
return { run: nowMsecsSinceEpoch >= TaskBackupPush.nextDueAt }
|
|
112
|
+
}
|
|
113
|
+
// Safety net for writers that never announced themselves.
|
|
114
|
+
return { run: nowMsecsSinceEpoch >= TaskBackupPush.lastRunAt + TaskBackupPush.IDLE_RECHECK_MS }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async runTask (): Promise<string> {
|
|
118
|
+
TaskBackupPush.checkNow = false
|
|
119
|
+
const startedAt = Date.now()
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
const r = await this.push()
|
|
123
|
+
|
|
124
|
+
// Opted out: a deliberate no-op, not a failure and not progress. noteRan keeps the
|
|
125
|
+
// interval floor so the monitor does not re-check every tick, and hasChanges is left
|
|
126
|
+
// alone — those records really are not backed up, and clearing the flag would claim
|
|
127
|
+
// otherwise if the user opts back in.
|
|
128
|
+
if (r.optedOut === true) {
|
|
129
|
+
TaskBackupPush.checkNow = false
|
|
130
|
+
TaskBackupPush.noteRan(startedAt)
|
|
131
|
+
return ''
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// An oversized chunk is a standing condition, not a transient hiccup: it will be
|
|
135
|
+
// oversized on every pass until the offending record is dealt with. It must NOT take
|
|
136
|
+
// the success path — that resets the backoff and, because the window has not closed,
|
|
137
|
+
// sets checkNow and re-runs on the very next monitor tick, which is a hot loop. Back
|
|
138
|
+
// off exactly as for a failure, and leave hasChanges set: those records are still not
|
|
139
|
+
// backed up, and nothing here should imply otherwise.
|
|
140
|
+
if (r.oversized === true) {
|
|
141
|
+
TaskBackupPush.checkNow = false
|
|
142
|
+
TaskBackupPush.lastError = 'backup chunk too large for the server'
|
|
143
|
+
TaskBackupPush.noteFailure(startedAt)
|
|
144
|
+
return 'backup: chunk too large for the server, skipped'
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
TaskBackupPush.noteRan(startedAt)
|
|
148
|
+
TaskBackupPush.backoffMs = TaskBackupPush.BASE_BACKOFF_MS
|
|
149
|
+
TaskBackupPush.lastError = undefined
|
|
150
|
+
TaskBackupPush.lastSuccessAt = startedAt
|
|
151
|
+
|
|
152
|
+
// A window that closed with nothing to send means the log has caught up. Anything
|
|
153
|
+
// else means there is more to drain, so keep the flag set for the next pass.
|
|
154
|
+
if (r.windowClosed && r.pushed === 0) {
|
|
155
|
+
TaskBackupPush.hasChanges = false
|
|
156
|
+
} else {
|
|
157
|
+
TaskBackupPush.checkNow = true
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return r.pushed > 0 ? `backup: pushed 1 chunk, ${r.bytes} bytes` : ''
|
|
161
|
+
} catch (e) {
|
|
162
|
+
const message = e instanceof Error ? e.message : String(e)
|
|
163
|
+
TaskBackupPush.lastError = message
|
|
164
|
+
TaskBackupPush.noteFailure(startedAt)
|
|
165
|
+
return `backup: push failed, retrying after ${TaskBackupPush.backoffMs}ms: ${message}`
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credits arriving PeerPay inbox payments when the device has signal.
|
|
3
|
+
*
|
|
4
|
+
* Triggering mirrors TaskSendOffline: gated on the app's single online signal,
|
|
5
|
+
* with an immediate pass on reconnect / foreground / requestNow and exponential
|
|
6
|
+
* backoff (10s → 5min) while auto-accept still has retryable work — and the
|
|
7
|
+
* same idle backoff after a clean pass so sitting on Home still credits new
|
|
8
|
+
* mail.
|
|
9
|
+
*
|
|
10
|
+
* All state is static and process-global BY DESIGN: the monitor is torn down
|
|
11
|
+
* and rebuilt on network switches and wallet rebuilds, and a pending inbox
|
|
12
|
+
* must survive that.
|
|
13
|
+
*/
|
|
14
|
+
import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
|
|
15
|
+
import type { Monitor } from '@bsv/wallet-toolbox-mobile'
|
|
16
|
+
|
|
17
|
+
export interface CreditInboxTaskResult {
|
|
18
|
+
accepted: number
|
|
19
|
+
attention: number
|
|
20
|
+
pending?: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class TaskCreditInbox extends WalletMonitorTask {
|
|
24
|
+
static taskName = 'CreditInbox'
|
|
25
|
+
|
|
26
|
+
static readonly BASE_BACKOFF_MS = 10_000
|
|
27
|
+
static readonly MAX_BACKOFF_MS = 300_000
|
|
28
|
+
|
|
29
|
+
/** An immediate pass has been requested. Consumed at the top of runTask. */
|
|
30
|
+
static checkNow = false
|
|
31
|
+
/** Last observation from the app's single online listener. Gates trigger. */
|
|
32
|
+
static onlineNow = false
|
|
33
|
+
/** The inbox may still have retryable work. Set pessimistically; a clean run clears it. */
|
|
34
|
+
static hasPending = false
|
|
35
|
+
static backoffMs = TaskCreditInbox.BASE_BACKOFF_MS
|
|
36
|
+
static nextDueAt = 0
|
|
37
|
+
/** Needs-attention count from the last successful pass, for the home-screen badge. */
|
|
38
|
+
static lastAttentionCount = 0
|
|
39
|
+
|
|
40
|
+
static noteConnectivity(online: boolean): void {
|
|
41
|
+
TaskCreditInbox.onlineNow = online
|
|
42
|
+
if (online) {
|
|
43
|
+
TaskCreditInbox.checkNow = true
|
|
44
|
+
TaskCreditInbox.backoffMs = TaskCreditInbox.BASE_BACKOFF_MS
|
|
45
|
+
TaskCreditInbox.nextDueAt = 0
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** New work may exist. Cheap to over-call: one idle pass clears it. */
|
|
50
|
+
static noteEnqueued(): void {
|
|
51
|
+
TaskCreditInbox.hasPending = true
|
|
52
|
+
TaskCreditInbox.backoffMs = TaskCreditInbox.BASE_BACKOFF_MS
|
|
53
|
+
TaskCreditInbox.nextDueAt = 0
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
static requestNow(): void {
|
|
57
|
+
TaskCreditInbox.checkNow = true
|
|
58
|
+
TaskCreditInbox.backoffMs = TaskCreditInbox.BASE_BACKOFF_MS
|
|
59
|
+
TaskCreditInbox.nextDueAt = 0
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
static resetForTests(): void {
|
|
63
|
+
TaskCreditInbox.checkNow = false
|
|
64
|
+
TaskCreditInbox.onlineNow = false
|
|
65
|
+
TaskCreditInbox.hasPending = false
|
|
66
|
+
TaskCreditInbox.backoffMs = TaskCreditInbox.BASE_BACKOFF_MS
|
|
67
|
+
TaskCreditInbox.nextDueAt = 0
|
|
68
|
+
TaskCreditInbox.lastAttentionCount = 0
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
constructor(
|
|
72
|
+
monitor: Monitor,
|
|
73
|
+
private readonly credit: () => Promise<CreditInboxTaskResult>,
|
|
74
|
+
private readonly now: () => number = () => Date.now(),
|
|
75
|
+
private readonly onAccepted?: (count: number) => void
|
|
76
|
+
) {
|
|
77
|
+
super(monitor, TaskCreditInbox.taskName)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
trigger(nowMsecsSinceEpoch: number): { run: boolean } {
|
|
81
|
+
if (!TaskCreditInbox.onlineNow) return { run: false }
|
|
82
|
+
if (TaskCreditInbox.checkNow) return { run: true }
|
|
83
|
+
const due = nowMsecsSinceEpoch >= TaskCreditInbox.nextDueAt
|
|
84
|
+
if (TaskCreditInbox.hasPending && due) return { run: true }
|
|
85
|
+
// Idle poll after a clean pass: nextDueAt > 0 means a backoff was scheduled.
|
|
86
|
+
if (TaskCreditInbox.nextDueAt > 0 && due) return { run: true }
|
|
87
|
+
return { run: false }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private scheduleNext(pending: boolean): void {
|
|
91
|
+
TaskCreditInbox.hasPending = pending
|
|
92
|
+
TaskCreditInbox.nextDueAt = this.now() + TaskCreditInbox.backoffMs
|
|
93
|
+
TaskCreditInbox.backoffMs = Math.min(TaskCreditInbox.backoffMs * 2, TaskCreditInbox.MAX_BACKOFF_MS)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async runTask(): Promise<string> {
|
|
97
|
+
TaskCreditInbox.checkNow = false
|
|
98
|
+
try {
|
|
99
|
+
const r = await this.credit()
|
|
100
|
+
TaskCreditInbox.lastAttentionCount = r.attention
|
|
101
|
+
this.scheduleNext(!!r.pending)
|
|
102
|
+
if (r.accepted > 0) {
|
|
103
|
+
try {
|
|
104
|
+
this.onAccepted?.(r.accepted)
|
|
105
|
+
} catch {
|
|
106
|
+
// A toast/sound failure must not turn a successful credit into a retry.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (r.accepted === 0 && r.attention === 0) return ''
|
|
110
|
+
return `credited ${r.accepted}, attention ${r.attention}${r.pending ? ', pending' : ''}\n`
|
|
111
|
+
} catch (e) {
|
|
112
|
+
this.scheduleNext(true)
|
|
113
|
+
return `CreditInbox failed: ${e instanceof Error ? e.message : String(e)}\n`
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retries unsent PeerPay outbox entries when the device has signal.
|
|
3
|
+
*
|
|
4
|
+
* Triggering mirrors TaskSendOffline: gated on the app's single online signal,
|
|
5
|
+
* with an immediate pass on reconnect / foreground / requestNow and exponential
|
|
6
|
+
* backoff (10s → 5min) while unsent rows remain. Delivery is idempotent.
|
|
7
|
+
* The first thrown retry stops the pass — remaining entries wait for the next
|
|
8
|
+
* backoff rather than compounding a down message box.
|
|
9
|
+
*
|
|
10
|
+
* All state is static and process-global BY DESIGN: the monitor is torn down
|
|
11
|
+
* and rebuilt on network switches and wallet rebuilds, and a pending outbox
|
|
12
|
+
* must survive that.
|
|
13
|
+
*/
|
|
14
|
+
import { WalletMonitorTask } from '@bsv/wallet-toolbox-mobile/out/src/monitor/tasks/WalletMonitorTask'
|
|
15
|
+
import type { Monitor } from '@bsv/wallet-toolbox-mobile'
|
|
16
|
+
import type { OutboxEntry } from '../peerpay/outbox'
|
|
17
|
+
|
|
18
|
+
export interface DrainOutboxResult {
|
|
19
|
+
retried: number
|
|
20
|
+
remaining: number
|
|
21
|
+
stopped?: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Retry unsent entries in order; the first throw aborts the rest. */
|
|
25
|
+
export async function drainUnsentEntries(args: {
|
|
26
|
+
entries: OutboxEntry[]
|
|
27
|
+
retry: (entry: OutboxEntry) => Promise<void>
|
|
28
|
+
}): Promise<DrainOutboxResult> {
|
|
29
|
+
let retried = 0
|
|
30
|
+
for (const entry of args.entries) {
|
|
31
|
+
await args.retry(entry)
|
|
32
|
+
retried++
|
|
33
|
+
}
|
|
34
|
+
return { retried, remaining: args.entries.length - retried, stopped: false }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class TaskDrainOutbox extends WalletMonitorTask {
|
|
38
|
+
static taskName = 'DrainOutbox'
|
|
39
|
+
|
|
40
|
+
static readonly BASE_BACKOFF_MS = 10_000
|
|
41
|
+
static readonly MAX_BACKOFF_MS = 300_000
|
|
42
|
+
|
|
43
|
+
/** An immediate pass has been requested. Consumed at the top of runTask. */
|
|
44
|
+
static checkNow = false
|
|
45
|
+
/** Last observation from the app's single online listener. Gates trigger. */
|
|
46
|
+
static onlineNow = false
|
|
47
|
+
/** The outbox may still hold unsent rows. Set pessimistically; a clean run clears it. */
|
|
48
|
+
static hasPending = false
|
|
49
|
+
static backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
|
|
50
|
+
static nextDueAt = 0
|
|
51
|
+
|
|
52
|
+
static noteConnectivity(online: boolean): void {
|
|
53
|
+
TaskDrainOutbox.onlineNow = online
|
|
54
|
+
if (online) {
|
|
55
|
+
TaskDrainOutbox.checkNow = true
|
|
56
|
+
TaskDrainOutbox.backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
|
|
57
|
+
TaskDrainOutbox.nextDueAt = 0
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** New work exists. Cheap to over-call: one idle drain clears it. */
|
|
62
|
+
static noteEnqueued(): void {
|
|
63
|
+
TaskDrainOutbox.hasPending = true
|
|
64
|
+
TaskDrainOutbox.backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
|
|
65
|
+
TaskDrainOutbox.nextDueAt = 0
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
static requestNow(): void {
|
|
69
|
+
TaskDrainOutbox.checkNow = true
|
|
70
|
+
TaskDrainOutbox.backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
|
|
71
|
+
TaskDrainOutbox.nextDueAt = 0
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
static resetForTests(): void {
|
|
75
|
+
TaskDrainOutbox.checkNow = false
|
|
76
|
+
TaskDrainOutbox.onlineNow = false
|
|
77
|
+
TaskDrainOutbox.hasPending = false
|
|
78
|
+
TaskDrainOutbox.backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
|
|
79
|
+
TaskDrainOutbox.nextDueAt = 0
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
constructor(
|
|
83
|
+
monitor: Monitor,
|
|
84
|
+
private readonly drain: () => Promise<DrainOutboxResult>,
|
|
85
|
+
private readonly now: () => number = () => Date.now(),
|
|
86
|
+
private readonly prune?: () => Promise<void>
|
|
87
|
+
) {
|
|
88
|
+
super(monitor, TaskDrainOutbox.taskName)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
trigger(nowMsecsSinceEpoch: number): { run: boolean } {
|
|
92
|
+
if (!TaskDrainOutbox.onlineNow) return { run: false }
|
|
93
|
+
return {
|
|
94
|
+
run: TaskDrainOutbox.checkNow || (TaskDrainOutbox.hasPending && nowMsecsSinceEpoch >= TaskDrainOutbox.nextDueAt)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private scheduleRetry(): void {
|
|
99
|
+
TaskDrainOutbox.hasPending = true
|
|
100
|
+
TaskDrainOutbox.nextDueAt = this.now() + TaskDrainOutbox.backoffMs
|
|
101
|
+
TaskDrainOutbox.backoffMs = Math.min(TaskDrainOutbox.backoffMs * 2, TaskDrainOutbox.MAX_BACKOFF_MS)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async runTask(): Promise<string> {
|
|
105
|
+
TaskDrainOutbox.checkNow = false
|
|
106
|
+
try {
|
|
107
|
+
const r = await this.drain()
|
|
108
|
+
if (r.stopped || r.remaining > 0) {
|
|
109
|
+
this.scheduleRetry()
|
|
110
|
+
} else {
|
|
111
|
+
TaskDrainOutbox.hasPending = false
|
|
112
|
+
TaskDrainOutbox.backoffMs = TaskDrainOutbox.BASE_BACKOFF_MS
|
|
113
|
+
}
|
|
114
|
+
await this.prune?.()
|
|
115
|
+
if (r.retried === 0 && !r.stopped && r.remaining === 0) return ''
|
|
116
|
+
return `drained ${r.retried}, remaining ${r.remaining}${r.stopped ? ', stopped early' : ''}\n`
|
|
117
|
+
} catch (e) {
|
|
118
|
+
this.scheduleRetry()
|
|
119
|
+
return `DrainOutbox failed: ${e instanceof Error ? e.message : String(e)}\n`
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|