diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index a9dbb36c04..a26fdac1c5 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -9,6 +9,7 @@ on:
pull_request:
branches:
- sprint
+ - codex/r3-release-baseline-to-sprint
- dev
- main
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 8a5680c736..07b6f5307c 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -10,6 +10,7 @@ on:
pull_request:
branches:
- sprint
+ - codex/r3-release-baseline-to-sprint
- dev
- main
- release/2.6.3
diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml
index 594604506c..fdb0c092e5 100644
--- a/android/app/src/debug/AndroidManifest.xml
+++ b/android/app/src/debug/AndroidManifest.xml
@@ -52,15 +52,6 @@
-
-
-
-
-
-
-
-
-
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index de838aa93e..1b21a28af9 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -60,9 +60,19 @@
-
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ios/hexa_keeper/hexa_keeper.entitlements b/ios/hexa_keeper/hexa_keeper.entitlements
index 2fba371611..176fe58afc 100644
--- a/ios/hexa_keeper/hexa_keeper.entitlements
+++ b/ios/hexa_keeper/hexa_keeper.entitlements
@@ -6,7 +6,8 @@
development
com.apple.developer.associated-domains
- applinks:bitcoinkeeper.app/app/prod
+ applinks:www.bitcoinkeeper.app
+ applinks:bitcoinkeeper.app
com.apple.developer.icloud-container-identifiers
diff --git a/ios/hexa_keeper_dev.entitlements b/ios/hexa_keeper_dev.entitlements
index bda8e1cf34..212d9955d9 100644
--- a/ios/hexa_keeper_dev.entitlements
+++ b/ios/hexa_keeper_dev.entitlements
@@ -6,7 +6,8 @@
development
com.apple.developer.associated-domains
- applinks:bitcoinkeeper.app/app/dev
+ applinks:www.bitcoinkeeper.app
+ applinks:bitcoinkeeper.app
com.apple.developer.icloud-container-identifiers
diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json
index 3a451be678..02441c17eb 100644
--- a/src/context/Localization/language/en.json
+++ b/src/context/Localization/language/en.json
@@ -449,6 +449,10 @@
"faucetDailyLimitTitle": "Daily Limit Reached",
"faucetDailyLimitBody": "You can request test sats up to 5 times per day. Try again after midnight UTC.",
"faucetDailyLimitError": "Daily limit reached. Try again after midnight UTC.",
+ "faucetPendingTitle": "Test sats are still pending",
+ "faucetPropagationPending": "The faucet sent test sats, but this wallet has not seen the transaction yet. Your balance may take a moment to update.",
+ "faucetSyncPending": "The faucet sent test sats, but the wallet could not sync. Check your server connection before requesting again.",
+ "faucetOutcomeUnknown": "The faucet request timed out. Test sats may already have been sent. Check your balance before requesting again.",
"Singlekey": "Single-key",
"multikey2of3": "2 of 3 multi-key",
"multikey3of5": "3 of 5 multi-key",
diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json
index 4670ae75db..00dd56df1c 100644
--- a/src/context/Localization/language/es.json
+++ b/src/context/Localization/language/es.json
@@ -437,6 +437,10 @@
"faucetDailyLimitTitle": "Daily Limit Reached",
"faucetDailyLimitBody": "You can request test sats up to 5 times per day. Try again after midnight UTC.",
"faucetDailyLimitError": "Daily limit reached. Try again after midnight UTC.",
+ "faucetPendingTitle": "Los sats de prueba siguen pendientes",
+ "faucetPropagationPending": "El grifo envió sats de prueba, pero la cartera aún no ve la transacción. El saldo puede tardar en actualizarse.",
+ "faucetSyncPending": "El grifo envió sats de prueba, pero la cartera no pudo sincronizarse. Comprueba la conexión al servidor antes de volver a solicitarlos.",
+ "faucetOutcomeUnknown": "La solicitud al grifo agotó el tiempo de espera. Puede que ya se hayan enviado sats de prueba. Comprueba el saldo antes de volver a solicitarlos.",
"Singlekey": "Single-key",
"multikey2of3": "2 of 3 multi-key",
"multikey3of5": "3 of 5 multi-key",
diff --git a/src/hooks/useTestSats.tsx b/src/hooks/useTestSats.tsx
index a413c2bdde..86910f60ab 100644
--- a/src/hooks/useTestSats.tsx
+++ b/src/hooks/useTestSats.tsx
@@ -8,6 +8,7 @@ import {
setTestCoinsFailed,
setTestCoinsReceived,
setTestCoinsQuotaReached,
+ setTestCoinsPending,
} from 'src/store/reducers/wallets';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import { useNavigation } from '@react-navigation/native';
@@ -19,9 +20,8 @@ import KeeperModal from 'src/components/KeeperModal';
const useTestSats = ({ wallet }) => {
const { setAppLoading, setLoadingContent } = useContext(AppContext);
- const { testCoinsReceived, testCoinsFailed, testCoinsQuotaReached } = useAppSelector(
- (state) => state.wallet
- );
+ const { testCoinsReceived, testCoinsFailed, testCoinsQuotaReached, testCoinsPending } =
+ useAppSelector((state) => state.wallet);
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
const { showToast } = useToastMessage();
const dispatch = useDispatch();
@@ -30,21 +30,33 @@ const useTestSats = ({ wallet }) => {
const navigation = useNavigation();
const { colorMode } = useColorMode();
const [quotaModalVisible, setQuotaModalVisible] = useState(false);
+ const [pendingModalKind, setPendingModalKind] = useState(null);
useEffect(() => {
- setAppLoading(false);
if (testCoinsReceived) {
+ setAppLoading(false);
showToast(walletText.recievedSats, );
- setTimeout(() => {
+ const timer = setTimeout(() => {
dispatch(setTestCoinsReceived(false));
navigation.goBack();
}, 3000);
+ return () => clearTimeout(timer);
} else if (testCoinsFailed) {
+ setAppLoading(false);
showToast(errorText.processFailed);
dispatch(setTestCoinsFailed(false));
}
+ return undefined;
}, [testCoinsReceived, testCoinsFailed]);
+ useEffect(() => {
+ if (testCoinsPending) {
+ setAppLoading(false);
+ setPendingModalKind(testCoinsPending);
+ dispatch(setTestCoinsPending(null));
+ }
+ }, [testCoinsPending]);
+
useEffect(() => {
if (testCoinsQuotaReached) {
setAppLoading(false);
@@ -105,6 +117,24 @@ const useTestSats = ({ wallet }) => {
buttonText={common.ok}
buttonCallback={() => setQuotaModalVisible(false)}
/>
+ setPendingModalKind(null)}
+ title={walletText.faucetPendingTitle}
+ subTitle={
+ pendingModalKind === 'unknown'
+ ? walletText.faucetOutcomeUnknown
+ : pendingModalKind === 'sync'
+ ? walletText.faucetSyncPending
+ : walletText.faucetPropagationPending
+ }
+ modalBackground={`${colorMode}.modalWhiteBackground`}
+ textColor={`${colorMode}.textGreen`}
+ subTitleColor={`${colorMode}.modalSubtitleBlack`}
+ showCloseIcon={false}
+ buttonText={common.ok}
+ buttonCallback={() => setPendingModalKind(null)}
+ />
>
);
};
diff --git a/src/hooks/useVault.ts b/src/hooks/useVault.ts
index e9a6309e95..d23b09311f 100644
--- a/src/hooks/useVault.ts
+++ b/src/hooks/useVault.ts
@@ -4,6 +4,7 @@ import { getJSONFromRealmObject } from 'src/storage/realm/utils';
import { useQuery } from '@realm/react';
import { VaultType, VisibilityType } from 'src/services/wallets/enums';
import { useAppSelector } from 'src/store/hooks';
+import { useMemo } from 'react';
type Params =
| {
@@ -25,19 +26,29 @@ const useVault = ({
getFirst = false,
getHiddenWallets = true,
}: Params) => {
- let allVaults: Vault[] = useQuery(RealmSchema.Vault);
-
+ const realmVaults = useQuery(RealmSchema.Vault) as unknown as Vault[];
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
- allVaults = includeArchived
- ? allVaults.map(getJSONFromRealmObject)
- : allVaults.filtered('archived != true').map(getJSONFromRealmObject);
- // Filter vaults based on network
- allVaults = allVaults.filter((wallet) => wallet.networkType === bitcoinNetworkType);
+ // Select before converting: toJSON traverses address, UTXO and history data.
+ // The useQuery reference changes on Realm writes, but stays stable across
+ // unrelated renders of the same screen.
+ const allVaultsIncludingCanary: Vault[] = useMemo(
+ () =>
+ realmVaults
+ .filter(
+ (vault) =>
+ (includeArchived || !vault.archived) && vault.networkType === bitcoinNetworkType
+ )
+ .map(getJSONFromRealmObject) as unknown as Vault[],
+ [realmVaults, includeArchived, bitcoinNetworkType]
+ );
//Filtering Canary Vaults from at all UI level where Vaults are consumed
- const allVaultsIncludingCanary = allVaults;
- allVaults = allVaults.filter((vault) => vault.type !== VaultType.CANARY);
- const allNonHiddenNonArchivedVaults = allVaults.filter(
- (vault) => vault.presentationData.visibility === VisibilityType.DEFAULT
+ const allVaults = useMemo(
+ () => allVaultsIncludingCanary.filter((vault) => vault.type !== VaultType.CANARY),
+ [allVaultsIncludingCanary]
+ );
+ const allNonHiddenNonArchivedVaults = useMemo(
+ () => allVaults.filter((vault) => vault.presentationData.visibility === VisibilityType.DEFAULT),
+ [allVaults]
);
if (!vaultId) {
if (getHiddenWallets) {
diff --git a/src/hooks/useWalletRefresh.ts b/src/hooks/useWalletRefresh.ts
new file mode 100644
index 0000000000..f1ba509f7c
--- /dev/null
+++ b/src/hooks/useWalletRefresh.ts
@@ -0,0 +1,59 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useDispatch } from 'react-redux';
+import { Vault } from 'src/services/wallets/interfaces/vault';
+import { Wallet } from 'src/services/wallets/interfaces/wallet';
+import { useAppSelector } from 'src/store/hooks';
+import {
+ clearRefreshRequest,
+ startRefreshRequest,
+} from 'src/store/reducers/wallets';
+import { autoSyncWallets, refreshWallets } from 'src/store/sagaActions/wallets';
+
+let nextRefreshRequest = 0;
+
+export const useWalletRefresh = () => {
+ const dispatch = useDispatch();
+ const [requestId, setRequestId] = useState(null);
+ const inFlight = useRef(null);
+ const status = useAppSelector((state) =>
+ requestId ? state.wallet.refreshRequests[requestId] : undefined
+ );
+
+ useEffect(() => {
+ if (requestId && status !== 'pending') {
+ inFlight.current = null;
+ setRequestId(null);
+ dispatch(clearRefreshRequest(requestId));
+ }
+ }, [dispatch, requestId, status]);
+
+ useEffect(() => () => {
+ if (inFlight.current) dispatch(clearRefreshRequest(inFlight.current));
+ }, [dispatch]);
+
+ const start = useCallback(
+ (actionForRequest: (id: string) => { type: string; payload: any }) => {
+ if (inFlight.current) return;
+ const id = `wallet-refresh-${Date.now()}-${++nextRefreshRequest}`;
+ inFlight.current = id;
+ dispatch(startRefreshRequest(id));
+ setRequestId(id);
+ dispatch(actionForRequest(id));
+ },
+ [dispatch]
+ );
+
+ const refresh = useCallback(
+ (wallets: (Wallet | Vault)[], options: { hardRefresh?: boolean; dustScan?: boolean }) => {
+ if (!wallets?.length || wallets.some((wallet) => !wallet)) return;
+ start((id) => refreshWallets(wallets, options, id));
+ },
+ [start]
+ );
+
+ const autoRefresh = useCallback(() => {
+ start((id) => autoSyncWallets(false, false, true, undefined, false, id));
+ }, [start]);
+
+ return { refreshing: !!requestId && status !== 'success' && status !== 'failure', refresh, autoRefresh };
+};
diff --git a/src/hooks/useWallets.tsx b/src/hooks/useWallets.tsx
index 79eb7aeee1..284e039d1f 100644
--- a/src/hooks/useWallets.tsx
+++ b/src/hooks/useWallets.tsx
@@ -2,46 +2,63 @@ import { Wallet } from 'src/services/wallets/interfaces/wallet';
import { RealmSchema } from 'src/storage/realm/enum';
import { getJSONFromRealmObject } from 'src/storage/realm/utils';
import { VisibilityType, WalletType } from 'src/services/wallets/enums';
-import { useObject, useQuery } from '@realm/react';
+import { useQuery } from '@realm/react';
import { useAppSelector } from 'src/store/hooks';
+import { useMemo } from 'react';
type useWalletsInterface = ({ getAll, walletIds }?: { getAll?: boolean; walletIds?: string[] }) => {
wallets: Wallet[];
};
+const filterByNetwork = (wallets: Wallet[], bitcoinNetworkType?: string): Wallet[] =>
+ bitcoinNetworkType
+ ? (wallets
+ .filter((wallet) => wallet.networkType === bitcoinNetworkType)
+ .map(getJSONFromRealmObject) as unknown as Wallet[])
+ : wallets;
+
const useWallets: useWalletsInterface = ({ walletIds = [], getAll = false } = {}) => {
const { bitcoinNetworkType } = useAppSelector((state) => state.settings);
- const allWallets: Wallet[] = useQuery(RealmSchema.Wallet).filter((wallet) =>
- [WalletType.DEFAULT, WalletType.IMPORTED].includes(wallet.type)
- );
-
- const filterByNetwork = (wallets) => {
- if (bitcoinNetworkType)
- return wallets
- .map(getJSONFromRealmObject)
- .filter((wallet) => wallet.networkType === bitcoinNetworkType);
- else return wallets;
- };
+ const realmWallets = useQuery(RealmSchema.Wallet) as unknown as Wallet[];
+ const validWalletIds = walletIds?.filter((item) => !!item) || [];
+ const walletIdsKey = JSON.stringify(validWalletIds);
+ const hasWalletIds = validWalletIds.length > 0;
+
+ // useQuery changes its collection reference when Realm reports an insert,
+ // deletion, or modification. Other screen renders can reuse this snapshot.
+ const listedWallets = useMemo(() => {
+ if (hasWalletIds && !getAll) return [];
+ const regularWallets = realmWallets.filter(
+ (wallet) => wallet.type === WalletType.DEFAULT || wallet.type === WalletType.IMPORTED
+ );
+ const visibleWallets = getAll
+ ? regularWallets
+ : regularWallets.filter(
+ (wallet) => wallet.presentationData.visibility == VisibilityType.DEFAULT
+ );
+ return filterByNetwork(visibleWallets, bitcoinNetworkType);
+ }, [realmWallets, bitcoinNetworkType, getAll, hasWalletIds]);
+
+ // Resolve IDs from the same reactive query. Calling useObject in a loop
+ // changes the number of hooks when a route gains or loses an ID.
+ const selectedWallets = useMemo(() => {
+ if (getAll || !hasWalletIds) return [];
+ const ids = JSON.parse(walletIdsKey) as string[];
+ const matched = ids
+ .map((id) => realmWallets.find((wallet) => wallet.id === id))
+ .filter((wallet): wallet is Wallet => !!wallet);
+ return filterByNetwork(matched, bitcoinNetworkType);
+ }, [realmWallets, bitcoinNetworkType, getAll, hasWalletIds, walletIdsKey]);
if (getAll) {
- return { wallets: filterByNetwork(allWallets) };
+ return { wallets: listedWallets };
}
- const allWalletsNonHidden = allWallets.filter(
- (wallet) => wallet.presentationData.visibility == VisibilityType.DEFAULT
- );
- walletIds = walletIds?.filter((item) => !!item);
- if (walletIds && walletIds.length) {
- const extractedWallets = [];
- for (let index = 0; index < walletIds.length; index += 1) {
- const id = walletIds[index];
- const wallet: Wallet = useObject(RealmSchema.Wallet, id);
- if (wallet) extractedWallets.push(wallet);
- }
- return { wallets: filterByNetwork(extractedWallets) };
+ if (hasWalletIds) {
+ return { wallets: selectedWallets };
}
- return { wallets: filterByNetwork(allWalletsNonHidden) };
+ return { wallets: listedWallets };
};
export default useWallets;
diff --git a/src/navigation/AppStateHandler.tsx b/src/navigation/AppStateHandler.tsx
index 342f2ab15e..34ef589e62 100644
--- a/src/navigation/AppStateHandler.tsx
+++ b/src/navigation/AppStateHandler.tsx
@@ -1,8 +1,9 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { AppState, Linking } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useDispatch } from 'react-redux';
import { setHasDeepLink } from 'src/store/reducers/login';
+import { autoSyncWallets } from 'src/store/sagaActions/wallets';
const PASSCODE_TIMEOUT = 5 * 60 * 1000;
@@ -11,28 +12,29 @@ const AppStateHandler = () => {
const [appState, setAppState] = useState(AppState.currentState);
const [lastBackgroundTime, setLastBackgroundTime] = useState(null);
const dispatch = useDispatch();
- let triggeredDeepLink = null;
+ const triggeredDeepLink = useRef(null);
useEffect(() => {
- Linking.addEventListener('url', (event) => {
- if (event.url) triggeredDeepLink = event.url;
+ const subscription = Linking.addEventListener('url', (event) => {
+ if (event.url) triggeredDeepLink.current = event.url;
});
- // cleanup is performed in initialAppController for all url events at once.
+ return () => subscription.remove();
+ }, []);
+ useEffect(() => {
const handleAppStateChange = (nextAppState) => {
if (appState === 'active' && nextAppState.match(/inactive|background/)) {
setLastBackgroundTime(Date.now());
} else if (appState.match(/inactive|background/) && nextAppState === 'active') {
// App is coming to the foreground, check elapsed time
const state = navigation.getState();
- const notLoginStack = state?.routes[state.index]?.name !== 'LoginStack';
-
- if (
- notLoginStack &&
- lastBackgroundTime &&
- Date.now() - lastBackgroundTime > PASSCODE_TIMEOUT
- ) {
- dispatch(setHasDeepLink(triggeredDeepLink));
+ const activeRoute = state?.routes[state.index];
+ const notLoginStack = activeRoute?.name !== 'LoginStack';
+ const timedOut = lastBackgroundTime && Date.now() - lastBackgroundTime > PASSCODE_TIMEOUT;
+
+ if (notLoginStack && timedOut) {
+ dispatch(setHasDeepLink(triggeredDeepLink.current));
+ triggeredDeepLink.current = null;
navigation.reset({
index: 0,
routes: [
@@ -44,6 +46,14 @@ const AppStateHandler = () => {
},
],
});
+ } else if (activeRoute?.name === 'App') {
+ // The transient login.isAuthenticated flag is cleared after unlock.
+ // Only an active, unlocked app session should poll archived Vaults.
+ const childState = activeRoute.state;
+ const childRoute = childState?.routes[childState.index || 0];
+ if (childRoute?.name !== 'Login') {
+ dispatch(autoSyncWallets(false, false, false, undefined, true));
+ }
}
}
setAppState(nextAppState);
diff --git a/src/navigation/remoteKeyDeepLink.ts b/src/navigation/remoteKeyDeepLink.ts
new file mode 100644
index 0000000000..7df197c51a
--- /dev/null
+++ b/src/navigation/remoteKeyDeepLink.ts
@@ -0,0 +1,25 @@
+const REMOTE_KEY_PATH = /^\/app\/(dev|prod)\/remote\/([0-9a-f]{24})\/?$/;
+
+/** Return only links generated for this build's remote-key exchange. */
+export function getRemoteKeyFromDeepLink(rawUrl: string, environment: string): string | null {
+ const expectedStage = environment === 'PRODUCTION' ? 'prod' : environment === 'DEVELOPMENT' ? 'dev' : null;
+ if (!expectedStage) return null;
+
+ try {
+ const url = new URL(rawUrl);
+ if (
+ url.protocol !== 'https:' ||
+ !['bitcoinkeeper.app', 'www.bitcoinkeeper.app'].includes(url.hostname) ||
+ url.port ||
+ url.username ||
+ url.password
+ ) {
+ return null;
+ }
+
+ const match = REMOTE_KEY_PATH.exec(url.pathname);
+ return match?.[1] === expectedStage ? match[2] : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/src/screens/AppSettings/Node/NodeSettings.tsx b/src/screens/AppSettings/Node/NodeSettings.tsx
index dc74de79ca..4e88a8327e 100644
--- a/src/screens/AppSettings/Node/NodeSettings.tsx
+++ b/src/screens/AppSettings/Node/NodeSettings.tsx
@@ -1,5 +1,5 @@
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useCallback, useContext, useState } from 'react';
import { StyleSheet, FlatList } from 'react-native';
import { hp, wp } from 'src/constants/responsive';
import { LocalizationContext } from 'src/context/Localization/LocContext';
@@ -19,7 +19,7 @@ import DowngradeToPleb from 'src/assets/images/downgradetopleb.svg';
import DowngradeToPlebDark from 'src/assets/images/downgradetoplebDark.svg';
import Buttons from 'src/components/Buttons';
import EmptyListIllustration from 'src/components/EmptyListIllustration';
-import { CommonActions, useNavigation } from '@react-navigation/native';
+import { CommonActions, useFocusEffect, useNavigation } from '@react-navigation/native';
import ServerItem from './components/ServerItem';
import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
import { updateAppImage } from 'src/store/sagaActions/bhr';
@@ -53,15 +53,14 @@ function NodeSettings() {
const [nodeToDisconnect, setNodeToDisconnect] = useState(null);
const [nodeToDelete, setNodeToDelete] = useState(null);
- const isNodeListEmpty = nodeList.length === 0;
const isNoNodeConnected =
!ELECTRUM_CLIENT.isClientConnected && nodeList.every((node) => !node.isConnected);
- const nodes: NodeDetail[] = Node.getAllNodes();
-
- useEffect(() => {
- setNodeList(nodes);
- }, [nodes.length]);
+ useFocusEffect(
+ useCallback(() => {
+ setNodeList(Node.getAllNodes());
+ }, [])
+ );
const onDelete = async (selectedItem: NodeDetail) => {
const isConnected = Node.nodeConnectionStatus(selectedItem);
@@ -76,56 +75,54 @@ function NodeSettings() {
};
const onConnectToNode = async (selectedNode: NodeDetail) => {
- let updatedNodes = Node.getAllNodes();
-
- // Disconnect the currently connected node if it's not the selected one
- const currentlySelectedNode = updatedNodes.find((node) => node.isConnected);
- if (currentlySelectedNode && currentlySelectedNode.id !== selectedNode.id) {
- await Node.disconnect(currentlySelectedNode);
- currentlySelectedNode.isConnected = false;
- Node.update(currentlySelectedNode, { isConnected: currentlySelectedNode.isConnected });
- updatedNodes = updatedNodes.map((node) =>
- node.id === currentlySelectedNode.id ? { ...currentlySelectedNode } : node
- );
- }
-
dispatch(electrumClientConnectionInitiated());
setLoading(true);
-
- const { connected, connectedTo, error } = await Node.connectToSelectedNode(selectedNode);
-
- if (connected) {
- selectedNode.isConnected = connected;
- Node.update(selectedNode, { isConnected: connected });
- dispatch(electrumClientConnectionExecuted({ successful: connected, connectedTo }));
- showToast(`${errorString.ConnectedTo} ${connectedTo}`, );
- } else {
- dispatch(electrumClientConnectionExecuted({ successful: connected, error }));
+ try {
+ const currentlySelectedNode = Node.getAllNodes().find((node) => node.isConnected);
+ if (currentlySelectedNode && currentlySelectedNode.id !== selectedNode.id) {
+ Node.disconnect(currentlySelectedNode);
+ Node.update(currentlySelectedNode, { isConnected: false });
+ }
+
+ const { connected, connectedTo, error } = await Node.connectToSelectedNode(selectedNode);
+ if (connected) {
+ Node.update(selectedNode, { isConnected: true });
+ dispatch(electrumClientConnectionExecuted({ successful: true, connectedTo }));
+ showToast(`${errorString.ConnectedTo} ${connectedTo}`, );
+ } else {
+ dispatch(electrumClientConnectionExecuted({ successful: false, error }));
+ }
+ } catch (error) {
+ dispatch(
+ electrumClientConnectionExecuted({
+ successful: false,
+ error: error?.message || String(error),
+ })
+ );
+ } finally {
+ setLoading(false);
+ setNodeList(Node.getAllNodes());
}
-
- updatedNodes = updatedNodes.map((node) =>
- node.id === selectedNode.id ? { ...selectedNode } : node
- );
- setNodeList(updatedNodes);
- setLoading(false);
};
const onDisconnectToNode = async (selectedNode: NodeDetail) => {
try {
setLoading(true);
Node.disconnect(selectedNode);
- selectedNode.isConnected = false;
- Node.update(selectedNode, { isConnected: selectedNode.isConnected });
- showToast(`${errorString.disconnectedFrom} ${selectedNode.host}`, );
-
- const updatedNodes = nodeList.map((node) =>
- node.id === selectedNode.id ? { ...selectedNode } : node
+ Node.update(selectedNode, { isConnected: false });
+ dispatch(
+ electrumClientConnectionExecuted({
+ successful: false,
+ error: 'Disconnected from Electrum server',
+ })
);
- setNodeList(updatedNodes);
- setLoading(false);
+ showToast(`${errorString.disconnectedFrom} ${selectedNode.host}`, );
} catch (error) {
console.error('Error disconnecting electrum client', error);
showToast(errorString.failedToDiConnect, );
+ } finally {
+ setLoading(false);
+ setNodeList(Node.getAllNodes());
}
};
diff --git a/src/screens/HelpAi/HelpAiChat.tsx b/src/screens/HelpAi/HelpAiChat.tsx
index afd7bf0d2f..df90b185e5 100644
--- a/src/screens/HelpAi/HelpAiChat.tsx
+++ b/src/screens/HelpAi/HelpAiChat.tsx
@@ -11,6 +11,7 @@ import {
TextInput,
View,
} from 'react-native';
+import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import Buttons from 'src/components/Buttons';
import KeeperModal from 'src/components/KeeperModal';
@@ -37,11 +38,13 @@ import { useAppDispatch, useAppSelector } from 'src/store/hooks';
import {
appendHelpAiMessage,
createHelpAiThread,
+ discardHelpAiFailedMessage,
incrementHelpAiIssueCount,
setHelpAiChatMeta,
setHelpAiDraft,
setHelpAiDraftStatus,
setHelpAiEscalationStage,
+ setHelpAiFailedMessageId,
setHelpAiRawMessages,
type HelpAiDraftStatus,
type HelpAiRenderMessage,
@@ -65,6 +68,12 @@ import Fonts from 'src/constants/Fonts';
import ChatIcon from 'src/assets/images/chat.svg';
import { sanitizeHelpAiReplyLinks, sanitizeHelpAiSources } from 'src/utils/helpAiLinkPolicy';
import { detectSensitiveInput, detectSensitiveInDraft } from 'src/utils/helpAiSensitiveData';
+import {
+ canSendChatMessage,
+ findRetryableChatMessage,
+ isNearChatBottom,
+ planChatSend,
+} from 'src/utils/helpAiChatBehavior';
// Enhanced error handler to distinguish between all backend rate limit codes
const getHelpAiFriendlyError = (error: any, scope: 'chat' | 'issue'): string => {
@@ -139,6 +148,12 @@ const HelpAiChat = ({ navigation, route }) => {
const disclaimerPoints = [askAi.disclaimerPoint1, askAi.disclaimerPoint2, askAi.disclaimerPoint3];
const { showToast } = useToastMessage();
const listRef = useRef>(null);
+ const initialScrollPending = useRef(true);
+ const readingEarlier = useRef(false);
+ const userScrolling = useRef(false);
+ const forceFollow = useRef(false);
+ const sendingRef = useRef(false);
+ const discardedFailedMessageId = useRef(null);
const generatedConversationId = useMemo(() => `conv_${Date.now().toString(36)}`, []);
const conversationId = route?.params?.conversationId || generatedConversationId;
const initialPrompt = route?.params?.prefillText || '';
@@ -153,6 +168,7 @@ const HelpAiChat = ({ navigation, route }) => {
text: greetings.current,
};
const messages = persistedThread?.messages?.length ? persistedThread.messages : [defaultIntro];
+ const failedMessage = findRetryableChatMessage(messages, persistedThread?.failedMessageId);
const rawChatMessages = persistedThread?.rawMessages || [];
const draft = persistedThread?.draft || null;
const draftStatus: HelpAiDraftStatus = persistedThread?.draftStatus || 'pending_review';
@@ -163,7 +179,6 @@ const HelpAiChat = ({ navigation, route }) => {
const [input, setInput] = useState(initialPrompt);
const [sending, setSending] = useState(false);
const [typing, setTyping] = useState(false);
- const [lastFailedText, setLastFailedText] = useState(null);
const [showDisclaimerModal, setShowDisclaimerModal] = useState(false);
useEffect(() => {
@@ -181,16 +196,28 @@ const HelpAiChat = ({ navigation, route }) => {
setShowDisclaimerModal(false);
};
- const scrollToBottom = () => {
- requestAnimationFrame(() => listRef.current?.scrollToEnd({ animated: true }));
+ const scrollToBottom = (animated: boolean) => {
+ requestAnimationFrame(() => listRef.current?.scrollToEnd({ animated }));
};
- useEffect(() => {
- if (!messages.length) return undefined;
- // Small delay to let FlatList measure new content before scrolling
- const t = setTimeout(scrollToBottom, 150);
- return () => clearTimeout(t);
- }, [messages.length]);
+ const updateReadingPosition = (event: NativeSyntheticEvent) => {
+ if (!userScrolling.current) return;
+ const { contentOffset, layoutMeasurement, contentSize } = event.nativeEvent;
+ readingEarlier.current = !isNearChatBottom(
+ contentOffset.y,
+ layoutMeasurement.height,
+ contentSize.height
+ );
+ };
+
+ const handleContentSizeChange = (_width: number, height: number) => {
+ if (height <= 0) return;
+ if (initialScrollPending.current || forceFollow.current || !readingEarlier.current) {
+ scrollToBottom(!initialScrollPending.current);
+ }
+ initialScrollPending.current = false;
+ forceFollow.current = false;
+ };
const appendMessage = (message: HelpAiRenderMessage) => {
dispatch(appendHelpAiMessage({ conversationId, message }));
@@ -214,23 +241,38 @@ const HelpAiChat = ({ navigation, route }) => {
}
};
- const sendToChat = async (text: string) => {
- if (!text.trim()) return;
+ const sendToChat = async (text: string, retryMessageId?: string) => {
+ if (sendingRef.current) return;
+ if (retryMessageId && retryMessageId === discardedFailedMessageId.current) return;
+ if (!canSendChatMessage(failedMessage?.id, retryMessageId)) {
+ showToast('Retry or discard the unsent message first.');
+ return;
+ }
+ const retryMessage = findRetryableChatMessage(messages, retryMessageId);
+ if (retryMessageId && !retryMessage) return;
+ const { outboundText, appendUserMessage } = planChatSend(text, retryMessage);
+ if (!outboundText) return;
if (!appId) {
showToast('Missing app id. Please restart the app and try again.');
return;
}
- const sensitiveResult = detectSensitiveInput(text.trim());
+ const sensitiveResult = detectSensitiveInput(outboundText);
if (sensitiveResult) {
showToast(sensitiveResult.message);
return;
}
- const outboundText = text.trim();
- setInput('');
+ const messageId = retryMessageId || nowId();
+ sendingRef.current = true;
+ forceFollow.current = true;
+ readingEarlier.current = false;
+ if (appendUserMessage) {
+ setInput('');
+ dispatch(setHelpAiFailedMessageId({ conversationId, messageId: null }));
+ appendMessage({ id: messageId, type: 'user', text: outboundText });
+ }
setSending(true);
setTyping(true);
- appendMessage({ id: nowId(), type: 'user', text: outboundText });
try {
const metadata = chatMeta || (await buildMetadata());
@@ -286,16 +328,23 @@ const HelpAiChat = ({ navigation, route }) => {
dispatch(appendHelpAiMessage({ conversationId, message: escalationRenderMsg }));
}
});
- setLastFailedText(null);
+ dispatch(setHelpAiFailedMessageId({ conversationId, messageId: null }));
} catch (error) {
showToast(getHelpAiFriendlyError(error, 'chat'));
- setLastFailedText(outboundText);
+ dispatch(setHelpAiFailedMessageId({ conversationId, messageId }));
} finally {
+ sendingRef.current = false;
setSending(false);
setTyping(false);
}
};
+ const discardFailedMessage = () => {
+ if (!failedMessage || sendingRef.current) return;
+ discardedFailedMessageId.current = failedMessage.id;
+ dispatch(discardHelpAiFailedMessage({ conversationId }));
+ };
+
const submitDraftIssue = async () => {
if (!draft || !chatMeta) return;
if (!appId) {
@@ -496,6 +545,24 @@ const HelpAiChat = ({ navigation, route }) => {
)}
contentContainerStyle={styles.messagesContainer}
keyboardShouldPersistTaps="handled"
+ onContentSizeChange={handleContentSizeChange}
+ onScrollBeginDrag={() => {
+ userScrolling.current = true;
+ forceFollow.current = false;
+ }}
+ onScroll={updateReadingPosition}
+ onScrollEndDrag={(event) => {
+ updateReadingPosition(event);
+ userScrolling.current = false;
+ }}
+ onMomentumScrollBegin={() => {
+ userScrolling.current = true;
+ }}
+ onMomentumScrollEnd={(event) => {
+ updateReadingPosition(event);
+ userScrolling.current = false;
+ }}
+ scrollEventThrottle={16}
ListFooterComponent={
<>
{typing && (
@@ -558,12 +625,12 @@ const HelpAiChat = ({ navigation, route }) => {
style={[
styles.sendBtn,
{
- opacity: sending ? 0.6 : 1,
- backgroundColor: Colors.primaryGreen,
- },
+ opacity: sending || failedMessage ? 0.6 : 1,
+ backgroundColor: Colors.primaryGreen,
+ },
]}
onPress={() => sendToChat(input)}
- disabled={sending}
+ disabled={sending || !!failedMessage}
>
{isDarkMode ? (
@@ -574,12 +641,32 @@ const HelpAiChat = ({ navigation, route }) => {
- {lastFailedText ? (
- sendToChat(lastFailedText)}>
-
- Retry last failed message
+ {failedMessage ? (
+
+
+ Message not sent. Retry or discard it before sending another.
-
+
+ sendToChat(failedMessage.text, failedMessage.id)}
+ disabled={sending}
+ >
+
+ Retry
+
+
+
+
+ Discard
+
+
+
+
) : null}
{
+ const handleRemoteKeyDeepLink = async (encryptionKey: string) => {
dispatch(setAppWideLoading(true));
- const encryptionKey = initialUrl.split('remote/')[1];
const hash = getHashFromKey(encryptionKey);
if (encryptionKey && hash) {
try {
@@ -338,21 +339,17 @@ function InititalAppController({ navigation, electrumErrorVisible, setElectrumEr
async function handleDeepLinking() {
try {
const initialUrl = await Linking.getInitialURL();
- if (initialUrl) {
- if (initialUrl.includes('remote/')) {
- handleRemoteKeyDeepLink(initialUrl);
- }
- }
+ if (initialUrl) handleDeepLinkEvent({ url: initialUrl });
} catch (error) {
//
}
}
useEffect(() => {
- Linking.addEventListener('url', handleDeepLinkEvent);
- handleDeepLinking();
+ const subscription = Linking.addEventListener('url', handleDeepLinkEvent);
+ if (!hasDeepLink) handleDeepLinking();
return () => {
- Linking.removeAllListeners('url');
+ subscription.remove();
};
}, []);
diff --git a/src/screens/Home/components/Wallet/HomeWallet.tsx b/src/screens/Home/components/Wallet/HomeWallet.tsx
index f277a0b79a..e359467466 100644
--- a/src/screens/Home/components/Wallet/HomeWallet.tsx
+++ b/src/screens/Home/components/Wallet/HomeWallet.tsx
@@ -23,7 +23,7 @@ import CollaborativeWalletIcon from 'src/assets/images/collaborative_vault_white
import { useAppSelector } from 'src/store/hooks';
import { resetCollaborativeSession } from 'src/store/reducers/vaults';
import { useDispatch } from 'react-redux';
-import { autoSyncWallets, refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { RefreshControl } from 'react-native';
import { ELECTRUM_CLIENT } from 'src/services/electrum/client';
import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView';
@@ -123,7 +123,8 @@ const HomeWallet = () => {
const dispatch = useDispatch();
const [showAddWalletModal, setShowAddWalletModal] = useState(false);
const [collabSessionExistsModalVisible, setCollabSessionExistsModalVisible] = useState(false);
- const [pullRefresh, setPullRefresh] = useState(false);
+ const [navigateAfterSessionReset, setNavigateAfterSessionReset] = useState(false);
+ const { refreshing: pullRefresh, autoRefresh } = useWalletRefresh();
const { walletSyncing } = useAppSelector((state) => state.wallet);
const [pickWalletType, setPickWalletType] = useState(false);
const [createUsdtWallet, setCreateUsdtWallet] = useState(false);
@@ -157,23 +158,29 @@ const HomeWallet = () => {
}
}, [pendingDustToast]);
+ useEffect(() => {
+ if (navigateAfterSessionReset && Object.keys(collaborativeSession.signers).length === 0) {
+ setNavigateAfterSessionReset(false);
+ navigation.navigate('SetupCollaborativeWallet');
+ }
+ }, [navigateAfterSessionReset, collaborativeSession.signers, navigation]);
+
+ const resetAndStartCollaborativeWallet = () => {
+ dispatch(resetCollaborativeSession());
+ setNavigateAfterSessionReset(true);
+ };
+
const handleCollaborativeWalletCreation = () => {
setShowAddWalletModal(false);
if (Object.keys(collaborativeSession.signers).length > 0) {
setCollabSessionExistsModalVisible(true);
} else {
- dispatch(resetCollaborativeSession());
- setTimeout(() => {
- navigation.navigate('SetupCollaborativeWallet');
- }, 500); // delaying navigation by 0.5 second to ensure collaborative session reset
+ resetAndStartCollaborativeWallet();
}
};
const pullDownRefresh = () => {
- setPullRefresh(true);
-
- dispatch(autoSyncWallets(false, false, true));
- setPullRefresh(false);
+ autoRefresh();
};
const importUSDTWallet = async (mnemonic) => {
@@ -333,10 +340,7 @@ const HomeWallet = () => {
secondaryButtonText={common.startNew}
secondaryCallback={() => {
setCollabSessionExistsModalVisible(false);
- dispatch(resetCollaborativeSession());
- setTimeout(() => {
- navigation.navigate('SetupCollaborativeWallet');
- }, 500);
+ resetAndStartCollaborativeWallet();
}}
buttonCallback={() => {
setCollabSessionExistsModalVisible(false);
diff --git a/src/screens/SigningDevices/RemoteSharing.tsx b/src/screens/SigningDevices/RemoteSharing.tsx
index f029090868..1e1064ff6e 100644
--- a/src/screens/SigningDevices/RemoteSharing.tsx
+++ b/src/screens/SigningDevices/RemoteSharing.tsx
@@ -117,7 +117,7 @@ function RemoteSharing({ route }: ScreenProps) {
if (res?.id) {
const result = await Share.share({
title: RemoteShareText[mode].msgTitle,
- message: `${RemoteShareText[mode].msgDesc}\nhttps://bitcoinkeeper.app/${
+ message: `${RemoteShareText[mode].msgDesc}\nhttps://www.bitcoinkeeper.app/${
DeepLinkIdentifier[config.ENVIRONMENT]
}/remote/${encryptionKey}`,
});
diff --git a/src/screens/Vault/AllTransactions.tsx b/src/screens/Vault/AllTransactions.tsx
index ff3377922b..35638a64ea 100644
--- a/src/screens/Vault/AllTransactions.tsx
+++ b/src/screens/Vault/AllTransactions.tsx
@@ -1,13 +1,12 @@
import { FlatList, RefreshControl } from 'react-native';
-import React, { useState } from 'react';
+import React from 'react';
import { useColorMode } from '@gluestack-ui/themed-native-base';
import { useQuery } from '@realm/react';
-import { useDispatch } from 'react-redux';
import { RealmSchema } from 'src/storage/realm/enum';
import TransactionElement from 'src/components/TransactionElement';
import { getJSONFromRealmObject } from 'src/storage/realm/utils';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
import useVault from 'src/hooks/useVault';
import { EntityKind } from 'src/services/wallets/enums';
@@ -17,7 +16,6 @@ import WalletHeader from 'src/components/WalletHeader';
function AllTransactions({ route }) {
const { colorMode } = useColorMode();
- const dispatch = useDispatch();
const { title, entityKind, subtitle, vaultId = '' } = route?.params;
const { activeVault: vault } = useVault({ vaultId });
@@ -25,22 +23,17 @@ function AllTransactions({ route }) {
.map(getJSONFromRealmObject)
.filter((wallet) => !wallet.archived)[0];
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const vaultTrans: Transaction[] = vault?.specs?.transactions || [];
const walletTrans: Transaction[] = wallet?.specs.transactions || [];
+ const currentWallet = entityKind === EntityKind.WALLET ? wallet : vault;
const renderTransactionElement = ({ item }) => (
-
+
);
const pullDownRefresh = () => {
- setPullRefresh(true);
- refreshVault();
- setPullRefresh(false);
- };
-
- const refreshVault = () => {
- dispatch(refreshWallets([vault], { hardRefresh: true }));
+ refresh([currentWallet], { hardRefresh: true });
};
return (
diff --git a/src/screens/Vault/VaultDetails.tsx b/src/screens/Vault/VaultDetails.tsx
index 4ae46546d7..445866cd87 100644
--- a/src/screens/Vault/VaultDetails.tsx
+++ b/src/screens/Vault/VaultDetails.tsx
@@ -9,7 +9,7 @@ import SignerIcon from 'src/assets/images/keys-icon.svg';
import KeeperModal from 'src/components/KeeperModal';
import TransactionElement from 'src/components/TransactionElement';
import { MiniscriptTypes, VaultType } from 'src/services/wallets/enums';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { setIntroModal } from 'src/store/reducers/vaults';
import { useAppSelector } from 'src/store/hooks';
import { useDispatch } from 'react-redux';
@@ -157,7 +157,7 @@ function VaultDetails({ navigation, route }: ScreenProps) {
const dispatch = useDispatch();
const { showToast } = useToastMessage();
const { activeVault: vault } = useVault({ vaultId });
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const { vaultSigners: keys } = useSigners(vault.id);
const transactions = useMemo(
() =>
@@ -372,9 +372,7 @@ function VaultDetails({ navigation, route }: ScreenProps) {
}, [syncing, ELECTRUM_CLIENT]);
const syncVault = (hardRefresh) => {
- setPullRefresh(true);
- dispatch(refreshWallets([vault], { hardRefresh }));
- setPullRefresh(false);
+ refresh([vault], { hardRefresh });
};
const showTimelockModalContent = useCallback(() => {
diff --git a/src/screens/Vault/components/TransactionsAndUTXOs.tsx b/src/screens/Vault/components/TransactionsAndUTXOs.tsx
index b9d9be1d5b..c5ca3f4e9c 100644
--- a/src/screens/Vault/components/TransactionsAndUTXOs.tsx
+++ b/src/screens/Vault/components/TransactionsAndUTXOs.tsx
@@ -1,14 +1,13 @@
import { FlatList, RefreshControl, TouchableOpacity } from 'react-native';
-import React, { useContext, useState } from 'react';
+import React, { useContext } from 'react';
import { CommonActions, useNavigation } from '@react-navigation/native';
import TransactionElement from 'src/components/TransactionElement';
import { Vault } from 'src/services/wallets/interfaces/vault';
import { Box, HStack, VStack } from '@gluestack-ui/themed-native-base';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import EmptyStateView from 'src/components/EmptyView/EmptyStateView';
import NoVaultTransactionIcon from 'src/assets/images/emptystate.svg';
import IconArrowBlack from 'src/assets/images/icon_arrow_black.svg';
-import { useDispatch } from 'react-redux';
import Text from 'src/components/KeeperText';
import { windowHeight, wp } from 'src/constants/responsive';
import { EntityKind } from 'src/services/wallets/enums';
@@ -24,14 +23,11 @@ function TransactionsAndUTXOs({
autoRefresh: boolean;
}) {
const { colorMode } = useColorMode();
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const { translations } = useContext(LocalizationContext);
const { home } = translations;
- const dispatch = useDispatch();
const syncVault = () => {
- setPullRefresh(true);
- dispatch(refreshWallets([vault], { hardRefresh: true }));
- setPullRefresh(false);
+ refresh([vault], { hardRefresh: true });
};
const navigation = useNavigation();
@@ -71,6 +67,7 @@ function TransactionsAndUTXOs({
title: home.vaultTransactions,
subtitle: home.incommingAndOutgoing,
entityKind: EntityKind.VAULT,
+ vaultId: vault.id,
})
);
}}
diff --git a/src/screens/ViewTransactions/TransactionHistory.tsx b/src/screens/ViewTransactions/TransactionHistory.tsx
index c546c47ce8..5f2ab91977 100644
--- a/src/screens/ViewTransactions/TransactionHistory.tsx
+++ b/src/screens/ViewTransactions/TransactionHistory.tsx
@@ -1,28 +1,41 @@
import { FlatList, RefreshControl, StatusBar, StyleSheet } from 'react-native';
import { Box, useColorMode } from '@gluestack-ui/themed-native-base';
-import React, { use, useContext, useMemo, useState } from 'react';
+import React, { useContext, useMemo } from 'react';
import { hp, wp } from 'src/constants/responsive';
import { LocalizationContext } from 'src/context/Localization/LocContext';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
+import { Vault } from 'src/services/wallets/interfaces/vault';
import { CommonActions, useNavigation } from '@react-navigation/native';
import TransactionElement from 'src/components/TransactionElement';
import EmptyStateView from 'src/components/EmptyView/EmptyStateView';
import NoTransactionIcon from 'src/assets/images/noTransaction.svg';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { useDispatch } from 'react-redux';
import { setStateFromSnapshot } from 'src/store/reducers/send_and_receive';
import CurrencyTypeSwitch from 'src/components/Switch/CurrencyTypeSwitch';
import WalletHeader from 'src/components/WalletHeader';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import { useQuery } from '@realm/react';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { getJSONFromRealmObject } from 'src/storage/realm/utils';
+import { EntityKind } from 'src/services/wallets/enums';
function TransactionHistory({ route }) {
const { colorMode } = useColorMode();
const navigation = useNavigation();
const { translations } = useContext(LocalizationContext);
const { common, transactions: transactionsText } = translations;
- const { wallet }: { wallet: Wallet } = route.params;
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { wallet: routeWallet }: { wallet: Wallet | Vault } = route.params;
+ const walletRecord = useQuery(RealmSchema.Wallet, (collection) =>
+ collection.filtered('id == $0', routeWallet.id)
+ )[0];
+ const vaultRecord = useQuery(RealmSchema.Vault, (collection) =>
+ collection.filtered('id == $0', routeWallet.id)
+ )[0];
+ const record = routeWallet.entityKind === EntityKind.VAULT ? vaultRecord : walletRecord;
+ const wallet = record ? (getJSONFromRealmObject(record) as Wallet | Vault) : routeWallet;
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const dispatch = useDispatch();
const insets = useSafeAreaInsets();
const transactions = useMemo(
@@ -67,9 +80,7 @@ function TransactionHistory({ route }) {
);
const pullDownRefresh = () => {
- setPullRefresh(true);
- dispatch(refreshWallets([wallet], { hardRefresh: true }));
- setPullRefresh(false);
+ refresh([wallet], { hardRefresh: true });
};
return (
diff --git a/src/screens/WalletDetails/WalletDetails.tsx b/src/screens/WalletDetails/WalletDetails.tsx
index f5f9422437..ec901ff5ca 100644
--- a/src/screens/WalletDetails/WalletDetails.tsx
+++ b/src/screens/WalletDetails/WalletDetails.tsx
@@ -7,7 +7,7 @@ import AddWalletIcon from 'src/assets/images/addWallet_illustration.svg';
import TickIcon from 'src/assets/images/icon_tick.svg';
import { hp, wp } from 'src/constants/responsive';
import Text from 'src/components/KeeperText';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import { useWalletRefresh } from 'src/hooks/useWalletRefresh';
import { setIntroModal } from 'src/store/reducers/wallets';
import { useAppSelector } from 'src/store/hooks';
import useWallets from 'src/hooks/useWallets';
@@ -27,7 +27,7 @@ import ThemedColor from 'src/components/ThemedColor/ThemedColor';
import { useUTXOSpendability } from 'src/hooks/useUTXOSpendability';
// TODO: add type definitions to all components
-function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, wallet }) {
+function TransactionsAndUTXOs({ transactions, pullRefresh, onRefresh, wallet }) {
const { walletSyncing } = useAppSelector((state) => state.wallet);
const syncing = walletSyncing && wallet ? !!walletSyncing[wallet.id] : false;
@@ -36,9 +36,9 @@ function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, walle
>
);
@@ -69,7 +69,7 @@ function WalletDetails({ route }: ScreenProps) {
const { walletSyncing } = useAppSelector((state) => state.wallet);
const syncing = walletSyncing && wallet ? !!walletSyncing[wallet.id] : false;
const introModal = useAppSelector((state) => state.wallet.introModal) || false;
- const [pullRefresh, setPullRefresh] = useState(false);
+ const { refreshing: pullRefresh, refresh } = useWalletRefresh();
const viewAll_color = ThemedColor({ name: 'viewAll_color' });
useEffect(() => {
@@ -113,9 +113,7 @@ function WalletDetails({ route }: ScreenProps) {
}, [viewTransaction, wallet, navigation]);
const pullDownRefresh = (hardRefresh) => {
- setPullRefresh(true);
- dispatch(refreshWallets([wallet], { hardRefresh }));
- setPullRefresh(false);
+ refresh([wallet], { hardRefresh });
};
return (
@@ -179,9 +177,9 @@ function WalletDetails({ route }: ScreenProps) {
) : null}
pullDownRefresh(true)}
/>
) : (
diff --git a/src/screens/WalletDetails/components/Transactions.tsx b/src/screens/WalletDetails/components/Transactions.tsx
index 3e83162957..c893ffaf2a 100644
--- a/src/screens/WalletDetails/components/Transactions.tsx
+++ b/src/screens/WalletDetails/components/Transactions.tsx
@@ -1,7 +1,5 @@
import { FlatList, RefreshControl } from 'react-native';
-import React, { useContext, useEffect, useMemo, useState } from 'react';
-import { useDispatch } from 'react-redux';
-import { refreshWallets } from 'src/store/sagaActions/wallets';
+import React, { useContext, useEffect, useMemo } from 'react';
import EmptyStateView from 'src/components/EmptyView/EmptyStateView';
import NoTransactionIcon from 'src/assets/images/noTransaction.svg';
import TransactionElement from 'src/components/TransactionElement';
@@ -52,8 +50,8 @@ function Transactions({
pullRefresh,
currentWallet,
setInitialLoading,
+ onBitcoinRefresh,
}) {
- const dispatch = useDispatch();
const navigation = useNavigation();
const { translations } = useContext(LocalizationContext);
const { common } = translations;
@@ -80,16 +78,19 @@ function Transactions({
}, [transactions]);
const pullDownRefresh = async () => {
- setInitialLoading(true);
+ if (currentWallet.entityKind !== EntityKind.USDT_WALLET) {
+ onBitcoinRefresh?.();
+ return;
+ }
+ setPullRefresh?.(true);
+ setInitialLoading?.(true);
try {
- if (currentWallet.entityKind === EntityKind.USDT_WALLET) {
- await syncWallet(currentWallet);
- } else dispatch(refreshWallets([currentWallet], { hardRefresh: true }));
+ await syncWallet(currentWallet);
} catch (error) {
captureError(error);
} finally {
- setPullRefresh(false);
- setInitialLoading(false);
+ setPullRefresh?.(false);
+ setInitialLoading?.(false);
}
};
diff --git a/src/services/backend/Relay.ts b/src/services/backend/Relay.ts
index 9bcdcb3fe4..00df2bc0b1 100644
--- a/src/services/backend/Relay.ts
+++ b/src/services/backend/Relay.ts
@@ -223,32 +223,47 @@ export default class Relay {
public static getTestcoins = async (
recipientAddress: string,
- network: any,
+ network: NetworkType,
appId: string
): Promise<{
- txid: any;
- funded: any;
+ txid: string;
+ funded: boolean;
}> => {
- if (network === NetworkType.MAINNET) {
+ if (network !== NetworkType.TESTNET) {
throw new Error('Invalid network: failed to fund via testnet');
}
try {
- const res = await RestClient.post(`${config.RELAY}testnetFaucet`, {
- recipientAddress,
- appId,
- });
- const { txid, funded } = res.data;
+ const res = await RestClient.post(
+ `${config.RELAY}testnetFaucet`,
+ { recipientAddress, appId },
+ undefined,
+ { timeout: 20000 }
+ );
+ const { txid, funded } = res.data || {};
+ if (!funded || typeof txid !== 'string' || !/^[0-9a-f]{64}$/i.test(txid)) {
+ throw new Error('FAUCET_OUTCOME_UNKNOWN');
+ }
return {
txid,
funded,
};
} catch (err) {
+ if (err?.message === 'FAUCET_OUTCOME_UNKNOWN') throw err;
if (err.response?.status === 429) {
throw new Error('FAUCET_DAILY_LIMIT_REACHED');
}
- if (err.response) throw new Error(err.response.data.err);
- if (err.code) throw new Error(err.code);
+ if (
+ err?.code === 'ECONNABORTED' ||
+ err?.code === 'ETIMEDOUT' ||
+ err?.code === 'ERR_NETWORK' ||
+ err?.response?.status >= 500
+ ) {
+ // The relay may have broadcast before the response was lost. Never retry automatically.
+ throw new Error('FAUCET_OUTCOME_UNKNOWN');
+ }
+ if (err?.response) throw new Error(err.response.data?.err || 'FAUCET_REQUEST_FAILED');
+ throw new Error('FAUCET_REQUEST_FAILED');
}
};
@@ -302,7 +317,7 @@ export default class Relay {
public static checkTorStatus = async () => {
try {
- const response = await RestClient.get(TOR_ENDPOINT, { timeout: 20000 });
+ const response = await RestClient.get(TOR_ENDPOINT, undefined, { timeout: 20000 });
const data = (response as AxiosResponse).data || (response as any).json;
return data.IsTor;
} catch (error) {
diff --git a/src/services/electrum/client.ts b/src/services/electrum/client.ts
index 129db5a320..624e858514 100644
--- a/src/services/electrum/client.ts
+++ b/src/services/electrum/client.ts
@@ -2,11 +2,16 @@ import ElectrumCli from 'electrum-client';
import reverse from 'buffer-reverse';
import * as bitcoinJS from 'bitcoinjs-lib';
import { NodeDetail } from 'src/services/wallets/interfaces';
+import { NetworkType } from 'src/services/wallets/enums';
+import dbManager from 'src/storage/realm/dbManager';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { electrumClientConnectionExecuted } from 'src/store/reducers/login';
import { ElectrumTransaction, ElectrumUTXO } from './interface';
import torrific from './torrific';
import RestClient, { TorStatus } from '../rest/RestClient';
import ecc from '../wallets/operations/taproot-utils/noble_ecc';
import { store } from 'src/store/store';
+import { getFailoverPeers } from './peerSelection';
import {
classifyElectrumConnectionError,
ElectrumConnectionErrorType,
@@ -22,13 +27,66 @@ const ELECTRUM_CLIENT_CONFIG: {
reconnectDelay: 500, // retry after half a second
};
-const ELECTRUM_CLIENT_DEFAULTS = {
+type ElectrumClientState = {
+ electrumClient: any;
+ isClientConnected: boolean;
+ currentPeerIndex: number;
+ connectionAttempt: number;
+ activePeer: NodeDetail | null;
+ peers: NodeDetail[];
+ appId: string | null;
+ runtimeReconnectOrigin: NodeDetail | null;
+};
+
+const createElectrumClientState = (): ElectrumClientState => ({
electrumClient: null,
isClientConnected: false,
currentPeerIndex: -1,
connectionAttempt: 0,
activePeer: null,
peers: [],
+ appId: null,
+ runtimeReconnectOrigin: null,
+});
+
+let connectionGeneration = 0;
+
+export const ELECTRUM_CONNECTION_CHANGED_ERR = 'Electrum connection changed during request';
+
+const staleConnectionResult = () => ({
+ connected: false,
+ error: ELECTRUM_CONNECTION_CHANGED_ERR,
+ errorType: 'network' as ElectrumConnectionErrorType,
+});
+
+const selectionMatches = (state: ElectrumClientState): boolean => {
+ const current = store.getState();
+ const selectedNetwork = current.settings?.bitcoinNetworkType;
+ let realmMatches = true;
+ if (state.appId) {
+ try {
+ const keeper = dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as {
+ id?: string;
+ };
+ realmMatches = keeper?.id === state.appId;
+ } catch (_) {
+ realmMatches = false;
+ }
+ }
+ return (
+ state.appId === (current.storage?.appId ?? null) &&
+ realmMatches &&
+ (!selectedNetwork || !state.activePeer || state.activePeer.networkType === selectedNetwork)
+ );
+};
+
+const stateIsCurrent = (state: ElectrumClientState, generation: number): boolean =>
+ ELECTRUM_CLIENT === state && connectionGeneration === generation && selectionMatches(state);
+
+const networkTypeFor = (network: bitcoinJS.Network): NetworkType | null => {
+ if (network?.bech32 === bitcoinJS.networks.bitcoin.bech32) return NetworkType.MAINNET;
+ if (network?.bech32 === bitcoinJS.networks.testnet.bech32) return NetworkType.TESTNET;
+ return null;
};
let lastConnectionError: {
@@ -37,14 +95,7 @@ let lastConnectionError: {
} | null = null;
// eslint-disable-next-line import/no-mutable-exports
-export let ELECTRUM_CLIENT: {
- electrumClient: any;
- isClientConnected: boolean;
- currentPeerIndex: number;
- connectionAttempt: number;
- activePeer: NodeDetail;
- peers: NodeDetail[];
-} = ELECTRUM_CLIENT_DEFAULTS;
+export let ELECTRUM_CLIENT: ElectrumClientState = createElectrumClientState();
export const ELECTRUM_NOT_CONNECTED_ERR =
'Network Error: The current electrum node is not reachable, please try again with a different node';
@@ -55,47 +106,54 @@ export const ELECTRUM_NOT_CONNECTED_ERR_TOR =
export default class ElectrumClient {
public static connectOverTor = false;
- public static async connect() {
+ public static async connect(expectedGeneration = connectionGeneration) {
+ if (expectedGeneration !== connectionGeneration) return staleConnectionResult();
+ const state = ELECTRUM_CLIENT;
+ const peer = state.activePeer;
+ if (!selectionMatches(state)) return staleConnectionResult();
+
+ if (!peer) {
+ return {
+ connected: false,
+ error: 'Unable to connect to any electrum server. Please switch network and try again!',
+ generation: connectionGeneration,
+ };
+ }
+
+ const generation = ++connectionGeneration;
let timeoutId = null;
+ let client: ElectrumCli | null = null;
try {
- if (!ELECTRUM_CLIENT.activePeer) {
- console.log(
- 'Unable to connect to any electrum server. Please switch network and try again!'
- );
- return {
- connected: ELECTRUM_CLIENT.isClientConnected,
- error: 'Unable to connect to any electrum server. Please switch network and try again!',
- };
- }
+ state.isClientConnected = false;
+ if (state.electrumClient?.close) state.electrumClient.close();
ElectrumClient.connectOverTor =
- ELECTRUM_CLIENT.activePeer?.host?.endsWith('.onion') &&
- RestClient?.getTorStatus() === TorStatus.CONNECTED;
+ peer.host?.endsWith('.onion') && RestClient?.getTorStatus() === TorStatus.CONNECTED;
- ELECTRUM_CLIENT.electrumClient = new ElectrumCli(
+ client = new ElectrumCli(
ElectrumClient.connectOverTor ? torrific : global.net,
global.tls,
- ELECTRUM_CLIENT.activePeer.port,
- ELECTRUM_CLIENT.activePeer.host,
- ELECTRUM_CLIENT.activePeer.useSSL ? 'tls' : 'tcp'
+ peer.port,
+ peer.host,
+ peer.useSSL ? 'tls' : 'tcp'
); // tcp or tls
-
- ELECTRUM_CLIENT.electrumClient.onError = (error) => {
- if (ELECTRUM_CLIENT.isClientConnected) {
+ state.electrumClient = client;
+
+ client.onError = (error) => {
+ if (
+ stateIsCurrent(state, generation) &&
+ state.electrumClient === client &&
+ state.isClientConnected
+ ) {
console.log('Electrum mainClient.onError():', error?.message || error);
- if (ELECTRUM_CLIENT.electrumClient?.close) ELECTRUM_CLIENT.electrumClient.close();
-
- ELECTRUM_CLIENT.isClientConnected = false;
- ELECTRUM_CLIENT.activePeer.isConnected = false;
+ state.runtimeReconnectOrigin = state.runtimeReconnectOrigin || peer;
+ state.isClientConnected = false;
+ peer.isConnected = false;
+ if (client?.close) client.close();
console.log('Error: Close the connection');
-
- // setTimeout(
- // ElectrumClient.connect,
- // ELECTRUM_CLIENT.activePeer?.host?.endsWith('.onion') ? 4000 : 500
- // );
- return ElectrumClient.reconnect();
+ return ElectrumClient.reconnect(generation);
}
};
@@ -105,26 +163,44 @@ export default class ElectrumClient {
new Promise((resolve) => {
timeoutId = setTimeout(() => resolve('timeout'), 20000);
}),
- ELECTRUM_CLIENT.electrumClient.initElectrum({
+ client.initElectrum({
client: 'btc-k',
version: '1.4',
}), // should resolve within 4 seconds(prior to timeout)
]);
+ if (!stateIsCurrent(state, generation) || state.electrumClient !== client) {
+ if (client?.close) client.close();
+ return staleConnectionResult();
+ }
if (ver === 'timeout') throw new Error('Connection time-out');
if (ver && ver[0]) {
console.log('Connection to electrum server is established', {
ver,
- node: ELECTRUM_CLIENT.activePeer.host,
+ node: peer.host,
});
lastConnectionError = null;
- ELECTRUM_CLIENT.isClientConnected = true;
- ELECTRUM_CLIENT.activePeer.isConnected = true;
+ state.isClientConnected = true;
+ peer.isConnected = true;
+ state.connectionAttempt = 0;
+ if (state.runtimeReconnectOrigin) {
+ ElectrumClient.recordRuntimeRotation(
+ state,
+ state.runtimeReconnectOrigin,
+ peer,
+ generation
+ );
+ state.runtimeReconnectOrigin = null;
+ }
}
} catch (error) {
- ELECTRUM_CLIENT.isClientConnected = false;
- if (ELECTRUM_CLIENT.activePeer) ELECTRUM_CLIENT.activePeer.isConnected = false;
+ if (!stateIsCurrent(state, generation) || (client && state.electrumClient !== client)) {
+ if (client?.close) client.close();
+ return staleConnectionResult();
+ }
+ state.isClientConnected = false;
+ peer.isConnected = false;
const errorType = classifyElectrumConnectionError(error);
const errorMessage = error?.message || String(error);
@@ -132,7 +208,7 @@ export default class ElectrumClient {
type: errorType,
message: errorMessage,
};
- console.log('Bad connection:', JSON.stringify(ELECTRUM_CLIENT.activePeer), {
+ console.log('Bad connection:', JSON.stringify(peer), {
errorType,
message: errorMessage,
});
@@ -140,22 +216,31 @@ export default class ElectrumClient {
if (timeoutId) clearTimeout(timeoutId);
}
- if (ELECTRUM_CLIENT.isClientConnected) {
+ if (!stateIsCurrent(state, generation) || state.electrumClient !== client) {
+ return staleConnectionResult();
+ }
+ if (state.isClientConnected) {
return {
- connected: ELECTRUM_CLIENT.isClientConnected,
- connectedTo: ELECTRUM_CLIENT.activePeer.host,
+ connected: true,
+ connectedTo: peer.host,
+ generation,
};
}
- return ElectrumClient.reconnect();
+ return ElectrumClient.reconnect(generation);
}
- public static async reconnect() {
- ELECTRUM_CLIENT.connectionAttempt += 1;
+ public static async reconnect(expectedGeneration = connectionGeneration) {
+ if (expectedGeneration !== connectionGeneration) return staleConnectionResult();
+ const state = ELECTRUM_CLIENT;
+ if (!selectionMatches(state)) return staleConnectionResult();
+ const generation = ++connectionGeneration;
+ state.connectionAttempt += 1;
+ state.isClientConnected = false;
// close the connection before attempting again
- if (ELECTRUM_CLIENT.electrumClient?.close) ELECTRUM_CLIENT.electrumClient.close();
+ if (state.electrumClient?.close) state.electrumClient.close();
- if (ELECTRUM_CLIENT.connectionAttempt >= ELECTRUM_CLIENT_CONFIG.maxConnectionAttempt) {
+ if (state.connectionAttempt >= ELECTRUM_CLIENT_CONFIG.maxConnectionAttempt) {
const nextPeer = ElectrumClient.getNextPeer();
if (!nextPeer) {
const fallbackError =
@@ -168,23 +253,84 @@ export default class ElectrumClient {
error,
});
- return {
- connected: ELECTRUM_CLIENT.isClientConnected,
- error,
- errorType,
- };
+ if (state.runtimeReconnectOrigin && stateIsCurrent(state, generation)) {
+ store.dispatch(electrumClientConnectionExecuted({ successful: false, error }));
+ state.runtimeReconnectOrigin = null;
+ }
+ return { connected: false, error, errorType, generation };
}
- ELECTRUM_CLIENT.activePeer = nextPeer;
- ELECTRUM_CLIENT.connectionAttempt = 1;
+ state.activePeer = nextPeer;
+ state.connectionAttempt = 0;
console.log(`Attempting a connection with next peer: ${nextPeer?.host}`);
- return ElectrumClient.connect();
+ return ElectrumClient.connect(generation);
}
- console.log(`Reconnection attempt #${ELECTRUM_CLIENT.connectionAttempt}`);
+ console.log(`Reconnection attempt #${state.connectionAttempt}`);
await new Promise((resolve) => {
setTimeout(resolve, ELECTRUM_CLIENT_CONFIG.reconnectDelay); // attempts reconnection after 1 second
});
- return ElectrumClient.connect();
+ if (!stateIsCurrent(state, generation)) return staleConnectionResult();
+ return ElectrumClient.connect(generation);
+ }
+
+ private static recordRuntimeRotation(
+ state: ElectrumClientState,
+ previousPeer: NodeDetail,
+ connectedPeer: NodeDetail,
+ generation: number
+ ) {
+ if (!state.appId || !stateIsCurrent(state, generation)) return;
+ if (previousPeer.id !== connectedPeer.id) {
+ try {
+ if (!stateIsCurrent(state, generation)) return;
+ const previousSaved = dbManager.updateObjectById(
+ RealmSchema.NodeConnect,
+ previousPeer.id.toString(),
+ {
+ isConnected: false,
+ }
+ );
+ if (!stateIsCurrent(state, generation)) return;
+ const connectedSaved = dbManager.updateObjectById(
+ RealmSchema.NodeConnect,
+ connectedPeer.id.toString(),
+ {
+ isConnected: true,
+ }
+ );
+ if (!previousSaved || !connectedSaved) {
+ console.warn('Unable to save active Electrum server after failover');
+ }
+ } catch (error) {
+ console.warn('Unable to save active Electrum server after failover', error);
+ }
+ }
+ if (!stateIsCurrent(state, generation)) return;
+ store.dispatch(
+ electrumClientConnectionExecuted({ successful: true, connectedTo: connectedPeer.host })
+ );
+ }
+
+ public static getConnectionGeneration(): number {
+ return connectionGeneration;
+ }
+
+ public static assertConnectionGeneration(
+ expected: number,
+ expectedNetworkType?: NetworkType
+ ): void {
+ const state = ELECTRUM_CLIENT;
+ const selectedNetwork = store.getState().settings?.bitcoinNetworkType;
+ if (
+ !stateIsCurrent(state, expected) ||
+ !state.isClientConnected ||
+ !state.electrumClient ||
+ (expectedNetworkType &&
+ (state.activePeer?.networkType !== expectedNetworkType ||
+ (selectedNetwork && selectedNetwork !== expectedNetworkType)))
+ ) {
+ throw new Error(ELECTRUM_CONNECTION_CHANGED_ERR);
+ }
}
public static getNextPeer() {
@@ -200,22 +346,33 @@ export default class ElectrumClient {
public static forceDisconnect() {
if (!ELECTRUM_CLIENT.electrumClient) throw new Error('Electrum client not available');
- if (ELECTRUM_CLIENT.electrumClient?.close) ELECTRUM_CLIENT.electrumClient.close();
+ connectionGeneration += 1;
ELECTRUM_CLIENT.isClientConnected = false;
- ELECTRUM_CLIENT.activePeer.isConnected = false;
+ if (ELECTRUM_CLIENT.activePeer) ELECTRUM_CLIENT.activePeer.isConnected = false;
+ ELECTRUM_CLIENT.runtimeReconnectOrigin = null;
+ if (ELECTRUM_CLIENT.electrumClient?.close) ELECTRUM_CLIENT.electrumClient.close();
}
public static async serverFeatures() {
ElectrumClient.checkConnection();
-
- return ELECTRUM_CLIENT.electrumClient.server_features();
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
+ const features = await client.server_features();
+ ElectrumClient.assertConnectionGeneration(generation);
+ return features;
}
- public static getBlockchainHeaders = async (): Promise<{ height: number; hex: string }> =>
- ELECTRUM_CLIENT.electrumClient.blockchainHeaders_subscribe();
+ public static getBlockchainHeaders = async (): Promise<{ height: number; hex: string }> => {
+ ElectrumClient.checkConnection();
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
+ const headers = await client.blockchainHeaders_subscribe();
+ ElectrumClient.assertConnectionGeneration(generation);
+ return headers;
+ };
public static checkConnection() {
- if (!ELECTRUM_CLIENT.isClientConnected) {
+ if (!ELECTRUM_CLIENT.isClientConnected || !selectionMatches(ELECTRUM_CLIENT)) {
const connectionError = ElectrumClient.connectOverTor
? ELECTRUM_NOT_CONNECTED_ERR_TOR
: ELECTRUM_NOT_CONNECTED_ERR;
@@ -225,9 +382,12 @@ export default class ElectrumClient {
public static async ping() {
if (!ELECTRUM_CLIENT.electrumClient) throw new Error('Electrum client not available');
-
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
try {
- await ELECTRUM_CLIENT.electrumClient.server_ping();
+ ElectrumClient.assertConnectionGeneration(generation);
+ await client.server_ping();
+ ElectrumClient.assertConnectionGeneration(generation);
} catch (_) {
return false;
}
@@ -246,20 +406,35 @@ export default class ElectrumClient {
// if current peer to use is provided, it will use that peer
public static setActivePeer(nodes: NodeDetail[], currentPeerToUse?: NodeDetail) {
// close previous connection
- if (ELECTRUM_CLIENT.isClientConnected && ELECTRUM_CLIENT.electrumClient?.close) {
+ connectionGeneration += 1;
+ ELECTRUM_CLIENT.isClientConnected = false;
+ if (ELECTRUM_CLIENT.electrumClient?.close) {
ELECTRUM_CLIENT.electrumClient.close();
}
// set defaults
- ELECTRUM_CLIENT = ELECTRUM_CLIENT_DEFAULTS;
+ ELECTRUM_CLIENT = createElectrumClientState();
+ ELECTRUM_CLIENT.appId = store.getState().storage?.appId ?? null;
+ lastConnectionError = null;
// set active node
- let activeNode = currentPeerToUse || nodes.find((node) => node.isConnected);
+ const activeNode = currentPeerToUse || nodes.find((node) => node.isConnected);
ELECTRUM_CLIENT.activePeer = activeNode;
+ ELECTRUM_CLIENT.peers = getFailoverPeers(nodes, activeNode);
+ ELECTRUM_CLIENT.currentPeerIndex = activeNode ? 0 : -1;
+ }
- if (nodes) {
- ELECTRUM_CLIENT.peers = nodes;
- }
+ /** Extend a successful manual connection with eligible saved peers for later reconnects. */
+ public static setFailoverPeers(nodes: NodeDetail[], expectedGeneration?: number) {
+ if (
+ !ELECTRUM_CLIENT.isClientConnected ||
+ !selectionMatches(ELECTRUM_CLIENT) ||
+ (expectedGeneration !== undefined && expectedGeneration !== connectionGeneration)
+ )
+ return;
+ const activePeer = ELECTRUM_CLIENT.activePeer;
+ ELECTRUM_CLIENT.peers = getFailoverPeers(nodes, activePeer);
+ ELECTRUM_CLIENT.currentPeerIndex = activePeer ? 0 : -1;
}
public static splitIntoChunks(arr, chunkSize) {
@@ -277,9 +452,15 @@ export default class ElectrumClient {
): Promise<{ [address: string]: ElectrumUTXO[] }> {
ElectrumClient.checkConnection();
if (!network) network = store.getState().settings.bitcoinNetwork;
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
+ const expectedNetworkType = networkTypeFor(network);
+ if (!expectedNetworkType) throw new Error('Unsupported Bitcoin network');
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
const res = {};
const chunks = ElectrumClient.splitIntoChunks(addresses, batchsize);
for (let itr = 0; itr < chunks.length; itr += 1) {
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
const chunk = chunks[itr];
const scripthashes = [];
const scripthash2addr = {};
@@ -295,9 +476,8 @@ export default class ElectrumClient {
}
// eslint-disable-next-line no-await-in-loop
- const results = await ELECTRUM_CLIENT.electrumClient.blockchainScripthash_listunspentBatch(
- scripthashes
- );
+ const results = await client.blockchainScripthash_listunspentBatch(scripthashes);
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
for (let index = 0; index < results.length; index += 1) {
const utxos = results[index];
@@ -315,6 +495,7 @@ export default class ElectrumClient {
}
}
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
return res;
}
@@ -332,6 +513,11 @@ export default class ElectrumClient {
}
if (!network) network = store.getState().settings.bitcoinNetwork;
ElectrumClient.checkConnection();
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
+ const expectedNetworkType = networkTypeFor(network);
+ if (!expectedNetworkType) throw new Error('Unsupported Bitcoin network');
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
const historyByAddress = {};
const txids = [];
@@ -339,6 +525,7 @@ export default class ElectrumClient {
const chunks = ElectrumClient.splitIntoChunks(addresses, batchsize);
for (let itr = 0; itr < chunks.length; itr += 1) {
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
const chunk = chunks[itr];
const scripthashes = [];
const scripthash2addr = {};
@@ -354,9 +541,8 @@ export default class ElectrumClient {
}
// eslint-disable-next-line no-await-in-loop
- const results = await ELECTRUM_CLIENT.electrumClient.blockchainScripthash_getHistoryBatch(
- scripthashes
- );
+ const results = await client.blockchainScripthash_getHistoryBatch(scripthashes);
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
for (let index = 0; index < results.length; index += 1) {
const history = results[index];
@@ -373,6 +559,7 @@ export default class ElectrumClient {
}
}
+ ElectrumClient.assertConnectionGeneration(generation, expectedNetworkType);
return { historyByAddress, txids, txidToAddress };
}
@@ -386,6 +573,9 @@ export default class ElectrumClient {
return {};
}
ElectrumClient.checkConnection();
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
+ ElectrumClient.assertConnectionGeneration(generation);
const res = {};
txids = [...new Set(txids)]; // remove duplicates, if any
@@ -393,10 +583,12 @@ export default class ElectrumClient {
// lets try cache first
const chunks = ElectrumClient.splitIntoChunks(txids, batchsize);
for (const chunk of chunks) {
+ ElectrumClient.assertConnectionGeneration(generation);
let results = [];
// eslint-disable-next-line no-await-in-loop
- results = await ELECTRUM_CLIENT.electrumClient.blockchainTransaction_getBatch(chunk, verbose);
+ results = await client.blockchainTransaction_getBatch(chunk, verbose);
+ ElectrumClient.assertConnectionGeneration(generation);
for (const txdata of results) {
if (txdata.error && txdata.error.code === -32600) {
@@ -418,21 +610,27 @@ export default class ElectrumClient {
}
}
+ ElectrumClient.assertConnectionGeneration(generation);
return res;
}
public static async estimateFee(numberOfBlocks: number = 1) {
ElectrumClient.checkConnection();
-
- const feePerKB = await ELECTRUM_CLIENT.electrumClient.blockchainEstimatefee(numberOfBlocks); // in bitcoin
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
+ const feePerKB = await client.blockchainEstimatefee(numberOfBlocks); // in bitcoin
+ ElectrumClient.assertConnectionGeneration(generation);
if (feePerKB === -1) return 1;
return Math.round((feePerKB / 1024) * 1e8); // feePerByte(sats)
}
public static async broadcast(txHex: string) {
ElectrumClient.checkConnection();
-
- return ELECTRUM_CLIENT.electrumClient.blockchainTransaction_broadcast(txHex);
+ const generation = connectionGeneration;
+ const client = ELECTRUM_CLIENT.electrumClient;
+ const txid = await client.blockchainTransaction_broadcast(txHex);
+ ElectrumClient.assertConnectionGeneration(generation);
+ return txid;
}
public static async testConnection(node: NodeDetail) {
diff --git a/src/services/electrum/node.tsx b/src/services/electrum/node.tsx
index 1b09f62e35..29007cd312 100644
--- a/src/services/electrum/node.tsx
+++ b/src/services/electrum/node.tsx
@@ -91,9 +91,16 @@ export default class Node {
}
public static async connectToSelectedNode(selectedNode: NodeDetail) {
- // connects to the selected node
+ // The tapped node must connect on its own; only then enable eligible saved
+ // public peers for a later connection loss.
ElectrumClient.setActivePeer([], selectedNode);
- const { connected, connectedTo, error } = await ElectrumClient.connect();
+ const { connected, connectedTo, error, generation } = await ElectrumClient.connect();
+ if (connected) {
+ ElectrumClient.setFailoverPeers(
+ this.getAllNodes().filter((node) => node.networkType === selectedNode.networkType),
+ generation
+ );
+ }
return { connected, connectedTo, error };
}
diff --git a/src/services/electrum/peerSelection.ts b/src/services/electrum/peerSelection.ts
new file mode 100644
index 0000000000..6b706ed61c
--- /dev/null
+++ b/src/services/electrum/peerSelection.ts
@@ -0,0 +1,32 @@
+import { NodeDetail } from 'src/services/wallets/interfaces';
+import { NetworkType } from 'src/services/wallets/enums';
+import { predefinedMainnetNodes, predefinedTestnetNodes } from './predefinedNodes';
+
+const isPredefinedNode = (node: NodeDetail): boolean => {
+ const predefinedNodes =
+ node.networkType === NetworkType.TESTNET ? predefinedTestnetNodes : predefinedMainnetNodes;
+
+ return predefinedNodes.some(
+ (candidate) =>
+ candidate.id === node.id &&
+ candidate.host === node.host &&
+ candidate.port === node.port &&
+ candidate.useSSL === node.useSSL
+ );
+};
+
+/** Only a selected public server may fail over to other saved public servers. */
+export const getFailoverPeers = (nodes: NodeDetail[], selectedPeer: NodeDetail): NodeDetail[] => {
+ if (!selectedPeer) return [];
+ if (!isPredefinedNode(selectedPeer)) return [selectedPeer];
+
+ return [
+ selectedPeer,
+ ...nodes.filter(
+ (node) =>
+ node.networkType === selectedPeer.networkType &&
+ node.id !== selectedPeer.id &&
+ isPredefinedNode(node)
+ ),
+ ];
+};
diff --git a/src/services/electrum/predefinedNodes.ts b/src/services/electrum/predefinedNodes.ts
index 967ce7fac2..36436b95cf 100644
--- a/src/services/electrum/predefinedNodes.ts
+++ b/src/services/electrum/predefinedNodes.ts
@@ -11,6 +11,15 @@ export const predefinedTestnetNodes: NodeDetail[] = [
useSSL: true,
networkType: NetworkType.TESTNET,
},
+ {
+ id: 337,
+ host: 'bitcoin.stagemole.eu',
+ port: '5010',
+ isConnected: false,
+ useKeeperNode: false,
+ useSSL: true,
+ networkType: NetworkType.TESTNET,
+ },
];
export const predefinedMainnetNodes: NodeDetail[] = [
diff --git a/src/services/rest/RestClient.ts b/src/services/rest/RestClient.ts
index e505ec76f1..8ec9f70ed1 100644
--- a/src/services/rest/RestClient.ts
+++ b/src/services/rest/RestClient.ts
@@ -65,22 +65,29 @@ class RestClient {
path: string,
body: object,
headers?: object,
- options?: AxiosRequestConfig
+ options: AxiosRequestConfig = {}
): Promise {
return axios.post(path, body, {
...options,
headers: {
...RestClient.headers,
...headers,
+ ...options.headers,
},
});
}
- async get(path: string, headers?: object): Promise {
+ async get(
+ path: string,
+ headers?: object,
+ options: AxiosRequestConfig = {}
+ ): Promise {
return axios.get(path, {
+ ...options,
headers: {
...RestClient.headers,
...headers,
+ ...options.headers,
},
});
}
diff --git a/src/services/wallets/operations/index.ts b/src/services/wallets/operations/index.ts
index 7401a3ffcc..db29ee4324 100644
--- a/src/services/wallets/operations/index.ts
+++ b/src/services/wallets/operations/index.ts
@@ -382,7 +382,8 @@ export default class WalletOperations {
addresses: string[],
externalAddresses: { [address: string]: number },
internalAddresses: { [address: string]: number },
- network: bitcoinJS.Network
+ network: bitcoinJS.Network,
+ assertCurrentScope?: () => void
) => {
let transactions = wallet.specs.transactions;
let lastUsedAddressIndex = wallet.specs.nextFreeAddressIndex - 1;
@@ -395,6 +396,7 @@ export default class WalletOperations {
txidToIndex[transaction.txid] = index;
}
+ assertCurrentScope?.();
const { txids, txidToAddress } = await ElectrumClient.syncHistoryByAddress(addresses, network);
let newTxids = txids.filter((txid) => {
@@ -409,6 +411,7 @@ export default class WalletOperations {
)
);
+ assertCurrentScope?.();
const txs = await ElectrumClient.getTransactionsById(newTxids);
// fetch input transactions(for new ones), in order to construct the inputs
@@ -417,6 +420,7 @@ export default class WalletOperations {
if (txidToIndex[txid] !== undefined) continue; // transaction is already present(don't need to reconstruct using inputTxids)
for (const vin of txs[txid].vin) inputTxIds.push(vin.txid);
}
+ assertCurrentScope?.();
const inputTxs = await ElectrumClient.getTransactionsById(inputTxIds);
let hasNewUpdates = false;
@@ -483,7 +487,8 @@ export default class WalletOperations {
static syncWalletsViaElectrumClient = async (
wallets: (Wallet | Vault)[],
network: bitcoinJS.networks.Network,
- hardRefresh?: boolean
+ hardRefresh?: boolean,
+ assertCurrentScope?: () => void
): Promise<{
synchedWallets: SyncedWallet[];
}> => {
@@ -630,6 +635,7 @@ export default class WalletOperations {
currentRecheckInternal = wallet.specs.nextFreeChangeAddressIndex + gapLimit;
// sync utxos & balances
+ assertCurrentScope?.();
const utxosByAddress = await ElectrumClient.syncUTXOByAddress(
addresses.concat(
!hardRefresh && !walletHasNewUpdates
@@ -762,7 +768,8 @@ export default class WalletOperations {
addresses,
externalAddresses,
internalAddresses,
- network
+ network,
+ assertCurrentScope
);
walletHasNewUpdates =
diff --git a/src/store/reducers/helpAi.ts b/src/store/reducers/helpAi.ts
index 78489e77a1..ec7f17e54b 100644
--- a/src/store/reducers/helpAi.ts
+++ b/src/store/reducers/helpAi.ts
@@ -7,6 +7,7 @@ import {
HelpEscalationCard,
} from 'src/models/interfaces/HelpAi';
import { reduxStorage } from 'src/storage';
+import { removeFailedChatMessage } from 'src/utils/helpAiChatBehavior';
export type HelpAiDraftStatus =
| 'pending_review'
@@ -34,6 +35,7 @@ export type HelpAiThread = {
lastEscalationStage: string;
chatMeta: HelpChatMetadata | null;
issueCount: number;
+ failedMessageId: string | null;
};
type HelpAiState = {
@@ -66,6 +68,7 @@ const makeThread = (conversationId: string): HelpAiThread => ({
lastEscalationStage: 'none',
chatMeta: null,
issueCount: 1,
+ failedMessageId: null,
});
const findOrCreateThread = (state: HelpAiState, conversationId: string) => {
@@ -153,6 +156,29 @@ const helpAiSlice = createSlice({
thread.issueCount += 1;
thread.updatedAt = new Date().toISOString();
},
+ setHelpAiFailedMessageId: (
+ state,
+ action: PayloadAction<{ conversationId: string; messageId: string | null }>
+ ) => {
+ const thread = findOrCreateThread(state, action.payload.conversationId);
+ thread.failedMessageId = action.payload.messageId;
+ },
+ discardHelpAiFailedMessage: (state, action: PayloadAction<{ conversationId: string }>) => {
+ const thread = state.threads.find(
+ (item) => item.conversationId === action.payload.conversationId
+ );
+ if (!thread?.failedMessageId) return;
+ thread.messages = removeFailedChatMessage(thread.messages, thread.failedMessageId);
+ thread.failedMessageId = null;
+ const latestMessage = thread.messages[thread.messages.length - 1];
+ thread.lastMessage = latestMessage ? getMessagePreview(latestMessage) : '';
+ const firstUserMessage = thread.messages.find((message) => message.type === 'user');
+ thread.title =
+ firstUserMessage?.type === 'user'
+ ? firstUserMessage.text.trim().slice(0, 60) || 'New chat'
+ : 'New chat';
+ thread.updatedAt = new Date().toISOString();
+ },
},
});
@@ -166,6 +192,8 @@ export const {
setHelpAiEscalationStage,
setHelpAiChatMeta,
incrementHelpAiIssueCount,
+ setHelpAiFailedMessageId,
+ discardHelpAiFailedMessage,
} = helpAiSlice.actions;
const helpAiPersistConfig = {
@@ -174,4 +202,4 @@ const helpAiPersistConfig = {
whitelist: ['threads', 'activeConversationId'],
};
-export default persistReducer(helpAiPersistConfig, helpAiSlice.reducer);
\ No newline at end of file
+export default persistReducer(helpAiPersistConfig, helpAiSlice.reducer);
diff --git a/src/store/reducers/login.ts b/src/store/reducers/login.ts
index 99e122a497..8916f92a58 100644
--- a/src/store/reducers/login.ts
+++ b/src/store/reducers/login.ts
@@ -149,7 +149,7 @@ const loginSlice = createSlice({
setOfflineStatus: (state, action: PayloadAction) => {
state.isOffline = action.payload;
},
- setHasDeepLink: (state, action: PayloadAction) => {
+ setHasDeepLink: (state, action: PayloadAction) => {
state.hasDeepLink = action.payload;
},
clearHasCreds: (state) => {
diff --git a/src/store/reducers/network.ts b/src/store/reducers/network.ts
index e037782403..19e9e174d9 100644
--- a/src/store/reducers/network.ts
+++ b/src/store/reducers/network.ts
@@ -5,10 +5,12 @@ const initialState: {
exchangeRates: ExchangeRates;
averageTxFees: AverageTxFeesByNetwork;
initialNodesSaved: Boolean;
+ testnetFallbackNodeAddedByAppId: { [appId: string]: boolean };
} = {
exchangeRates: null,
averageTxFees: null,
initialNodesSaved: false,
+ testnetFallbackNodeAddedByAppId: {},
};
const networkSlice = createSlice({
@@ -26,9 +28,20 @@ const networkSlice = createSlice({
setInitialNodesSaved: (state, action: PayloadAction) => {
state.initialNodesSaved = action.payload;
},
+
+ setTestnetFallbackNodeAdded: (state, action: PayloadAction) => {
+ // Older persisted network state may not have the per-account map yet.
+ if (!state.testnetFallbackNodeAddedByAppId) state.testnetFallbackNodeAddedByAppId = {};
+ state.testnetFallbackNodeAddedByAppId[action.payload] = true;
+ },
},
});
-export const { setExchangeRates, setAverageTxFee, setInitialNodesSaved } = networkSlice.actions;
+export const {
+ setExchangeRates,
+ setAverageTxFee,
+ setInitialNodesSaved,
+ setTestnetFallbackNodeAdded,
+} = networkSlice.actions;
export default networkSlice.reducer;
diff --git a/src/store/reducers/wallets.ts b/src/store/reducers/wallets.ts
index 9e370fd404..b92b98e642 100644
--- a/src/store/reducers/wallets.ts
+++ b/src/store/reducers/wallets.ts
@@ -18,10 +18,12 @@ export type WalletsState = {
testCoinsReceived: boolean;
testCoinsFailed: boolean;
testCoinsQuotaReached: boolean;
+ testCoinsPending: 'propagation' | 'sync' | 'unknown' | null;
introModal: boolean;
err: string;
walletSyncing: {};
+ refreshRequests: Record;
signerPolicyError?: string;
};
@@ -38,11 +40,13 @@ const initialState: WalletsState = {
testCoinsReceived: false,
testCoinsFailed: false,
testCoinsQuotaReached: false,
+ testCoinsPending: null,
introModal: true,
err: '',
walletSyncing: {},
+ refreshRequests: {},
};
export type syncingPayload = {
@@ -66,6 +70,12 @@ const walletSlice = createSlice({
setTestCoinsQuotaReached: (state, action: PayloadAction) => {
state.testCoinsQuotaReached = action.payload;
},
+ setTestCoinsPending: (
+ state,
+ action: PayloadAction<'propagation' | 'sync' | 'unknown' | null>
+ ) => {
+ state.testCoinsPending = action.payload;
+ },
setIntroModal: (state, action: PayloadAction) => {
state.introModal = action.payload;
},
@@ -94,6 +104,23 @@ const walletSlice = createSlice({
},
resetSyncing: (state) => {
state.walletSyncing = {};
+ state.refreshRequests = {};
+ },
+ startRefreshRequest: (state, action: PayloadAction) => {
+ state.refreshRequests[action.payload] = 'pending';
+ },
+ finishRefreshRequest: (
+ state,
+ action: PayloadAction<{ requestId: string; succeeded: boolean }>
+ ) => {
+ if (state.refreshRequests[action.payload.requestId] === 'pending') {
+ state.refreshRequests[action.payload.requestId] = action.payload.succeeded
+ ? 'success'
+ : 'failure';
+ }
+ },
+ clearRefreshRequest: (state, action: PayloadAction) => {
+ delete state.refreshRequests[action.payload];
},
setSignerPolicyError: (state, action: PayloadAction) => {
state.signerPolicyError = action.payload;
@@ -114,12 +141,16 @@ export const {
setTestCoinsReceived,
setTestCoinsFailed,
setTestCoinsQuotaReached,
+ setTestCoinsPending,
setIntroModal,
walletGenerationFailed,
newWalletCreated,
resetWalletStateFlags,
resetSyncing,
setSyncing,
+ startRefreshRequest,
+ finishRefreshRequest,
+ clearRefreshRequest,
setSignerPolicyError,
} = walletSlice.actions;
@@ -130,10 +161,12 @@ const walletPersistConfig = {
'testCoinsReceived',
'testCoinsFailed',
'testCoinsQuotaReached',
+ 'testCoinsPending',
'hasNewWalletsGenerationFailed',
'hasNewWalletsGenerationSucceeded',
'isGeneratingNewWallet',
'walletSyncing',
+ 'refreshRequests',
'setSignerPolicyError',
],
};
diff --git a/src/store/sagaActions/wallets.ts b/src/store/sagaActions/wallets.ts
index b9078e1e3e..4d2c97a475 100644
--- a/src/store/sagaActions/wallets.ts
+++ b/src/store/sagaActions/wallets.ts
@@ -30,7 +30,9 @@ export const autoSyncWallets = (
syncAll?: boolean,
hardRefresh?: boolean,
addNotifications?: boolean,
- backupCheckAppId?: string
+ backupCheckAppId?: string,
+ archivedOnly?: boolean,
+ requestId?: string
) => ({
type: AUTO_SYNC_WALLETS,
payload: {
@@ -38,6 +40,8 @@ export const autoSyncWallets = (
hardRefresh,
addNotifications,
backupCheckAppId,
+ archivedOnly,
+ requestId,
},
});
@@ -61,12 +65,14 @@ export const updateSignerPolicy = (
export const refreshWallets = (
wallets: (Wallet | Vault)[],
- options: { hardRefresh?: boolean, dustScan?: boolean }
+ options: { hardRefresh?: boolean; dustScan?: boolean },
+ requestId?: string
) => ({
type: REFRESH_WALLETS,
payload: {
wallets,
options,
+ requestId,
},
});
diff --git a/src/store/sagas/bhr.ts b/src/store/sagas/bhr.ts
index ba417ac0e4..996d245f87 100644
--- a/src/store/sagas/bhr.ts
+++ b/src/store/sagas/bhr.ts
@@ -1094,10 +1094,11 @@ function* deleteBackupWorker() {
export const deleteBackupWatcher = createWatcher(deleteBackupWorker, DELETE_BACKUP);
-export function* checkBackupCondition() {
+export function* checkBackupCondition(expectedAppId?: string) {
const { automaticCloudBackup } = yield select((state: RootState) => state.bhr);
if (!automaticCloudBackup) return true;
const { id }: KeeperApp = yield call(dbManager.getObjectByIndex, RealmSchema.KeeperApp);
+ if (expectedAppId && id !== expectedAppId) return true;
markBackupMutation(id);
yield put(invalidateBackupRepair(id));
const netInfo = yield call(NetInfo.fetch);
diff --git a/src/store/sagas/faucetVisibility.ts b/src/store/sagas/faucetVisibility.ts
new file mode 100644
index 0000000000..6352bab485
--- /dev/null
+++ b/src/store/sagas/faucetVisibility.ts
@@ -0,0 +1,19 @@
+type VisibleWallet = {
+ specs?: {
+ confirmedUTXOs?: { txId: string }[];
+ unconfirmedUTXOs?: { txId: string }[];
+ balances?: { confirmed: number; unconfirmed: number };
+ };
+};
+
+/** A faucet transfer is visible only after its UTXO and balance were persisted. */
+export const isFaucetTxVisible = (wallet: VisibleWallet, txid: string): boolean => {
+ const specs = wallet?.specs;
+ if (!specs?.balances) return false;
+ // Home displays this sum. Do not announce receipt while it still shows zero.
+ if (!(specs.balances.confirmed + specs.balances.unconfirmed > 0)) return false;
+
+ return [...(specs.confirmedUTXOs || []), ...(specs.unconfirmedUTXOs || [])].some(
+ (utxo) => utxo.txId?.toLowerCase() === txid.toLowerCase()
+ );
+};
diff --git a/src/store/sagas/network.ts b/src/store/sagas/network.ts
index 4b847db49e..7e5788be8a 100644
--- a/src/store/sagas/network.ts
+++ b/src/store/sagas/network.ts
@@ -8,8 +8,8 @@ import {
} from 'src/services/electrum/predefinedNodes';
import ElectrumClient from 'src/services/electrum/client';
import { captureError } from 'src/services/sentry';
-import { setInitialNodesSaved } from '../reducers/network';
-import { RootState } from '../store';
+import { setInitialNodesSaved, setTestnetFallbackNodeAdded } from '../reducers/network';
+import { RootState, store } from '../store';
import {
electrumClientConnectionExecuted,
electrumClientConnectionInitiated,
@@ -18,9 +18,36 @@ import { createWatcher } from '../utilities';
import { fetchFeeRates } from '../sagaActions/send_and_receive';
import { CONNECT_TO_NODE } from '../sagaActions/network';
+let latestConnectWorker = 0;
+
export function* connectToNodeWorker() {
+ const workerId = ++latestConnectWorker;
+ let appId: string;
+ let bitcoinNetworkType: NetworkType;
+ let responseGeneration: number;
+ const contextIsCurrent = () => {
+ const current = store.getState();
+ let realmAppId: string;
+ try {
+ const keeper = dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as {
+ id?: string;
+ };
+ realmAppId = keeper?.id;
+ } catch (_) {
+ return false;
+ }
+ return (
+ workerId === latestConnectWorker &&
+ !!appId &&
+ realmAppId === appId &&
+ current.storage.appId === appId &&
+ current.settings.bitcoinNetworkType === bitcoinNetworkType
+ );
+ };
try {
- const { bitcoinNetworkType } = yield select((state: RootState) => state.settings);
+ bitcoinNetworkType = yield select((state: RootState) => state.settings.bitcoinNetworkType);
+ appId = yield select((state: RootState) => state.storage.appId);
+ if (!contextIsCurrent()) return;
console.log('Connecting to node...');
yield put(electrumClientConnectionInitiated());
@@ -29,8 +56,11 @@ export function* connectToNodeWorker() {
);
if (!areInitialNodesSaved) {
+ if (!contextIsCurrent()) return;
const currentNodes = yield call(dbManager.getCollection, RealmSchema.NodeConnect);
+ if (!contextIsCurrent()) return;
const defaultNodes = yield call(dbManager.getCollection, RealmSchema.DefaultNodeConnect);
+ if (!contextIsCurrent()) return;
let addInitialNode = defaultNodes && defaultNodes.length != 0;
if (!addInitialNode && currentNodes.length == 0) {
addInitialNode = true;
@@ -41,26 +71,110 @@ export function* connectToNodeWorker() {
bitcoinNetworkType === NetworkType.TESTNET
? predefinedTestnetNodes
: predefinedMainnetNodes;
- dbManager.createObjectBulk(RealmSchema.NodeConnect, hardcodedInitialNodes);
+ if (!contextIsCurrent()) return;
+ const created = yield call(
+ dbManager.createObjectBulk,
+ RealmSchema.NodeConnect,
+ hardcodedInitialNodes
+ );
+ if (!contextIsCurrent()) return;
+ if (!created) throw new Error('Unable to save initial Electrum servers');
}
+ if (!contextIsCurrent()) return;
yield put(setInitialNodesSaved(true));
}
+ // Existing Testnet installations only saved the first public server. Add the
+ // second once when that original server is still saved; an explicit deletion
+ // after this migration must not be undone at every reconnect.
+ const fallbackNodeAdded = yield select(
+ (state: RootState) => state.network.testnetFallbackNodeAddedByAppId?.[appId]
+ );
+ if (bitcoinNetworkType === NetworkType.TESTNET && appId && !fallbackNodeAdded) {
+ if (!contextIsCurrent()) return;
+ const savedNodes = yield call(dbManager.getCollection, RealmSchema.NodeConnect);
+ if (!contextIsCurrent()) return;
+ const originalNode = predefinedTestnetNodes[0];
+ const fallbackNode = predefinedTestnetNodes[1];
+ if (
+ savedNodes.some(
+ (node) =>
+ node.id === originalNode.id &&
+ node.host === originalNode.host &&
+ node.port === originalNode.port
+ ) &&
+ !savedNodes.some((node) => node.id === fallbackNode.id)
+ ) {
+ if (!contextIsCurrent()) return;
+ const created = yield call(dbManager.createObject, RealmSchema.NodeConnect, fallbackNode);
+ if (!contextIsCurrent()) return;
+ if (!created) throw new Error('Unable to save Testnet fallback server');
+ }
+ if (!contextIsCurrent()) return;
+ yield put(setTestnetFallbackNodeAdded(appId));
+ }
+
+ if (!contextIsCurrent()) return;
const nodes = (yield call(dbManager.getCollection, RealmSchema.NodeConnect)).filter(
(node) => node.networkType === bitcoinNetworkType
);
+ if (!contextIsCurrent()) return;
+ const selectedNode = nodes.find((node) => node.isConnected);
ElectrumClient.setActivePeer(nodes);
- const { connected, connectedTo, error } = yield call(ElectrumClient.connect);
+ const { connected, connectedTo, error, generation } = yield call(ElectrumClient.connect);
+ responseGeneration = generation;
+ const connectionIsCurrent = () => {
+ return contextIsCurrent() && generation === ElectrumClient.getConnectionGeneration();
+ };
+ // Another login/network request may replace this connection while the worker
+ // is waiting. Its result must not overwrite the newer connection's status.
+ if (!connectionIsCurrent()) return;
if (connected) {
+ const connectedNode = ElectrumClient.getActivePeer();
+ if (selectedNode && connectedNode?.id !== selectedNode.id) {
+ if (!connectionIsCurrent()) return;
+ yield call(
+ dbManager.updateObjectById,
+ RealmSchema.NodeConnect,
+ selectedNode.id.toString(),
+ {
+ isConnected: false,
+ }
+ );
+ if (!connectionIsCurrent()) return;
+ yield call(
+ dbManager.updateObjectById,
+ RealmSchema.NodeConnect,
+ connectedNode.id.toString(),
+ {
+ isConnected: true,
+ }
+ );
+ }
+ if (!connectionIsCurrent()) return;
yield put(electrumClientConnectionExecuted({ successful: connected, connectedTo }));
} else {
+ if (!connectionIsCurrent()) return;
yield put(electrumClientConnectionExecuted({ successful: connected, error }));
}
+ if (!connectionIsCurrent()) return;
yield put(fetchFeeRates());
} catch (err) {
+ if (
+ !contextIsCurrent() ||
+ (responseGeneration !== undefined &&
+ responseGeneration !== ElectrumClient.getConnectionGeneration())
+ )
+ return;
captureError(err);
+ yield put(
+ electrumClientConnectionExecuted({
+ successful: false,
+ error: err?.message || 'Unable to connect to Electrum server',
+ })
+ );
}
}
diff --git a/src/store/sagas/utxos.ts b/src/store/sagas/utxos.ts
index 7f3d1addec..5845863f1c 100644
--- a/src/store/sagas/utxos.ts
+++ b/src/store/sagas/utxos.ts
@@ -2,7 +2,7 @@ import dbManager from 'src/storage/realm/dbManager';
import { RealmSchema } from 'src/storage/realm/enum';
import { call, delay, fork, put, takeLatest } from 'redux-saga/effects';
import { BIP329Label, UTXO, UTXOSpendability } from 'src/services/wallets/interfaces';
-import { EntityKind, LabelRefType } from 'src/services/wallets/enums';
+import { EntityKind, LabelRefType, NetworkType } from 'src/services/wallets/enums';
import Relay from 'src/services/backend/Relay';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
import { generateAbbreviatedOutputDescriptors } from 'src/utils/service-utilities/utils';
@@ -25,6 +25,28 @@ import {
updateVaultImageWorker,
} from './bhr';
import { encrypt, generateEncryptionKey, hash256 } from 'src/utils/service-utilities/encryption';
+import { store } from '../store';
+
+type LabelSyncScope = { appId: string; networkType: NetworkType };
+
+const isCurrentLabelScope = (scope?: LabelSyncScope) =>
+ !scope ||
+ (store.getState().storage.appId === scope.appId &&
+ store.getState().settings.bitcoinNetworkType === scope.networkType);
+
+// Realm identity and tag writes must happen without a saga yield between them.
+const persistScopedLabels = (
+ addedTags: BIP329Label[],
+ deletedTagIds: string[],
+ scope?: LabelSyncScope
+): KeeperApp | null => {
+ if (!isCurrentLabelScope(scope)) return null;
+ const keeperApp = dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp;
+ if (!keeperApp || (scope && keeperApp.id !== scope.appId)) return null;
+ dbManager.createObjectBulk(RealmSchema.Tags, addedTags);
+ for (const element of deletedTagIds) dbManager.deleteObjectById(RealmSchema.Tags, element);
+ return keeperApp;
+};
export function* addLabelsWorker({
payload,
@@ -93,11 +115,13 @@ export function* bulkUpdateLabelsWorker({
txId?: string;
address?: string;
wallet: Wallet;
+ scope?: LabelSyncScope;
};
}) {
try {
yield put(setSyncingUTXOs(true));
- const { labelChanges, wallet, UTXO, txId, address } = payload;
+ const { labelChanges, wallet, UTXO, txId, address, scope } = payload;
+ if (scope && (!isCurrentLabelScope(scope) || wallet.networkType !== scope.networkType)) return;
const origin = generateAbbreviatedOutputDescriptors(wallet);
let addedTags: BIP329Label[] = [];
let deletedTagIds: string[] = [];
@@ -117,17 +141,18 @@ export function* bulkUpdateLabelsWorker({
if (labelChanges.deleted) {
deletedTagIds = labelChanges.deleted.map((label) => `${ref}${label.name}`);
}
- const { primarySeed, id }: KeeperApp = yield call(
- dbManager.getObjectByIndex,
- RealmSchema.KeeperApp
+ const keeperApp: KeeperApp | null = yield call(
+ persistScopedLabels,
+ addedTags,
+ deletedTagIds,
+ scope
);
- yield call(dbManager.createObjectBulk, RealmSchema.Tags, addedTags);
- for (const element of deletedTagIds) {
- yield call(dbManager.deleteObjectById, RealmSchema.Tags, element);
- }
+ if (!keeperApp) return;
+ const { primarySeed, id } = keeperApp;
try {
- const backupResponse = yield call(checkBackupCondition);
- if (!backupResponse) {
+ if (!isCurrentLabelScope(scope)) return;
+ const backupResponse = yield call(checkBackupCondition, scope?.appId);
+ if (!backupResponse && isCurrentLabelScope(scope)) {
const encryptionKey = generateEncryptionKey(primarySeed);
const tagsToBackup = addedTags.map((tag) => ({
id: hash256(hash256(encryptionKey + tag.id)),
diff --git a/src/store/sagas/walletRefreshCoordinator.js b/src/store/sagas/walletRefreshCoordinator.js
new file mode 100644
index 0000000000..0aaa9406e6
--- /dev/null
+++ b/src/store/sagas/walletRefreshCoordinator.js
@@ -0,0 +1,41 @@
+// The wallet watcher forks each request. Keep overlapping refreshes in order so
+// an older snapshot cannot persist after a newer one for the same wallet.
+const activeBatches = new Map();
+const walletTails = new Map();
+
+export const acquireWalletRefresh = (appId, networkType, wallets, options = {}) => {
+ const walletKeys = [...new Set(wallets.map((wallet) =>
+ JSON.stringify([appId, networkType, wallet.entityKind, wallet.id])
+ ))].sort();
+ const batchKey = JSON.stringify([
+ walletKeys,
+ !!options.hardRefresh,
+ !!options.addNotifications,
+ !!options.dustScan,
+ ]);
+ const existing = activeBatches.get(batchKey);
+ if (existing) return { owner: false, done: existing.done };
+
+ let resolveDone;
+ const done = new Promise((resolve) => { resolveDone = resolve; });
+ const predecessors = walletKeys.map((key) => walletTails.get(key)).filter(Boolean);
+ const ready = Promise.all(predecessors);
+ let completed = false;
+ const lease = {
+ owner: true,
+ ready,
+ done,
+ complete: (succeeded) => {
+ if (completed) return;
+ completed = true;
+ if (activeBatches.get(batchKey) === lease) activeBatches.delete(batchKey);
+ for (const key of walletKeys) {
+ if (walletTails.get(key) === done) walletTails.delete(key);
+ }
+ resolveDone(succeeded);
+ },
+ };
+ activeBatches.set(batchKey, lease);
+ for (const key of walletKeys) walletTails.set(key, done);
+ return lease;
+};
diff --git a/src/store/sagas/walletSyncSelection.js b/src/store/sagas/walletSyncSelection.js
new file mode 100644
index 0000000000..4e27514569
--- /dev/null
+++ b/src/store/sagas/walletSyncSelection.js
@@ -0,0 +1,19 @@
+// Archived vaults remain in the local Realm even when they have no balance.
+// Keep them in the automatic sync set so a later deposit is discovered.
+export const selectWalletsForSync = (
+ wallets,
+ vaults,
+ networkType,
+ { syncAll = false, archivedOnly = false } = {}
+) => {
+ const onNetwork = (wallet) => wallet.networkType === networkType;
+ const archived = vaults.filter((vault) => vault.archived && onNetwork(vault));
+ const active = archivedOnly
+ ? []
+ : [...wallets, ...vaults.filter((vault) => !vault.archived)].filter(
+ (wallet) =>
+ onNetwork(wallet) && (syncAll || wallet.presentationData.visibility === 'DEFAULT')
+ );
+
+ return { active, archived };
+};
diff --git a/src/store/sagas/wallets.ts b/src/store/sagas/wallets.ts
index 839c894ca3..a11a4bdcda 100644
--- a/src/store/sagas/wallets.ts
+++ b/src/store/sagas/wallets.ts
@@ -6,6 +6,7 @@ import {
EntityKind,
MiniscriptTypes,
MultisigScriptType,
+ NetworkType,
SignerType,
VaultType,
VisibilityType,
@@ -26,13 +27,15 @@ import {
WalletImportDetails,
WalletPresentationData,
} from 'src/services/wallets/interfaces/wallet';
-import { call, delay, fork, put, select } from 'redux-saga/effects';
+import { call, delay, put, select } from 'redux-saga/effects';
import {
setSyncing,
setTestCoinsFailed,
setTestCoinsReceived,
setTestCoinsQuotaReached,
+ setTestCoinsPending,
setSignerPolicyError,
+ finishRefreshRequest,
} from 'src/store/reducers/wallets';
import { Alert } from 'react-native';
@@ -70,7 +73,9 @@ import {
sanitizeSeedKeyForBackup,
} from 'src/utils/utilities';
import { COLLABORATIVE_SCHEME } from 'src/screens/SigningDevices/SetupCollaborativeWallet';
-import { RootState } from '../store';
+import { RootState, store } from '../store';
+import { selectWalletsForSync } from './walletSyncSelection';
+import { acquireWalletRefresh } from './walletRefreshCoordinator';
import { checkBackupFreshness } from '../sagaActions/bhr';
import {
@@ -87,7 +92,6 @@ import {
TEST_SATS_RECIEVE,
UPDATE_SIGNER_POLICY,
UPDATE_WALLET_DETAILS,
- refreshWallets,
UPDATE_SIGNER_DETAILS,
UPDATE_KEY_DETAILS,
UPDATE_VAULT_DETAILS,
@@ -140,6 +144,9 @@ import { updateDelayedPolicyUpdate } from '../reducers/storage';
import { accountNoFromDerivationPath } from 'src/utils/service-utilities/utils';
import { classifyDustByAddress } from 'src/services/wallets/operations/dustClassification';
import { setPendingDustToast } from '../reducers/utxos';
+import { isFaucetTxVisible } from './faucetVisibility';
+
+const WALLET_SYNC_SCOPE_CHANGED = 'WALLET_SYNC_SCOPE_CHANGED';
export interface NewVaultDetails {
name?: string;
@@ -617,12 +624,15 @@ function* refreshWalletsWorker({
payload: {
wallets: (Wallet | Vault)[];
options: { hardRefresh?: boolean; addNotifications?: boolean; dustScan?: boolean };
+ requestId?: string;
};
}) {
- let { wallets, options } = payload;
+ let { wallets, options, requestId } = payload;
+ let succeeded = false;
+ let lease;
// Filter out pre-mix, post-mix, and bad bank wallets as they are no longer displayed or used.
- wallets = wallets.filter((wallet) => {
+ wallets = (wallets || []).filter((wallet) => {
if (
wallet.type === WalletType.PRE_MIX ||
wallet.type === WalletType.POST_MIX ||
@@ -634,13 +644,91 @@ function* refreshWalletsWorker({
});
try {
- if (!wallets || wallets.length === 0) return true;
+ const refreshScope = yield select((state: RootState) => ({
+ appId: state.storage.appId,
+ networkType: state.settings.bitcoinNetworkType,
+ }));
+ const assertAccountRealmScope = () => {
+ const currentState = store.getState();
+ let keeperApp: KeeperApp;
+ try {
+ keeperApp = dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp;
+ } catch {
+ throw new Error(WALLET_SYNC_SCOPE_CHANGED);
+ }
+ if (
+ currentState.storage.appId !== refreshScope.appId ||
+ currentState.settings.bitcoinNetworkType !== refreshScope.networkType ||
+ keeperApp?.id !== refreshScope.appId
+ )
+ throw new Error(WALLET_SYNC_SCOPE_CHANGED);
+ };
+ wallets = wallets.filter((wallet) => wallet.networkType === refreshScope.networkType);
+ if (wallets.length === 0) {
+ succeeded = true;
+ return true;
+ }
+
+ lease = acquireWalletRefresh(refreshScope.appId, refreshScope.networkType, wallets, options);
+ if (!lease.owner) {
+ succeeded = yield call(() => lease.done);
+ return succeeded;
+ }
+ yield call(() => lease.ready);
+ const readyScope = yield select((state: RootState) => ({
+ appId: state.storage.appId,
+ networkType: state.settings.bitcoinNetworkType,
+ }));
+ if (
+ readyScope.appId !== refreshScope.appId ||
+ readyScope.networkType !== refreshScope.networkType
+ )
+ return false;
+
+ // A queued refresh must start from the latest persisted specs, and a
+ // stale route must never supply a snapshot from another profile.
+ const currentWallets: (Wallet | Vault)[] = [];
+ for (const wallet of wallets) {
+ const schema =
+ wallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet;
+ const currentWallet = yield call(() => {
+ assertAccountRealmScope();
+ return dbManager.getObjectById(schema, wallet.id);
+ });
+ if (!currentWallet || currentWallet.networkType !== refreshScope.networkType) return false;
+ currentWallets.push(getJSONFromRealmObject(currentWallet));
+ }
+ wallets = currentWallets;
- if (!ELECTRUM_CLIENT.isClientConnected) {
+ let connectionMatchesScope = false;
+ try {
+ ElectrumClient.assertConnectionGeneration(
+ ElectrumClient.getConnectionGeneration(),
+ refreshScope.networkType
+ );
+ connectionMatchesScope = true;
+ } catch {
+ // Reconnect using the current account's saved nodes below.
+ }
+ if (!ELECTRUM_CLIENT.isClientConnected || !connectionMatchesScope) {
ElectrumClient.resetCurrentPeerIndex();
yield call(connectToNodeWorker);
}
+ assertAccountRealmScope();
+ if (!ELECTRUM_CLIENT.isClientConnected) throw new Error(ELECTRUM_NOT_CONNECTED_ERR);
+
+ const connectionGeneration = ElectrumClient.getConnectionGeneration();
+ const assertCurrentScope = () => {
+ assertAccountRealmScope();
+ try {
+ ElectrumClient.assertConnectionGeneration(connectionGeneration, refreshScope.networkType);
+ } catch {
+ throw new Error(ELECTRUM_NOT_CONNECTED_ERR);
+ }
+ };
+ assertCurrentScope();
+
yield put(setSyncing({ wallets, isSyncing: true }));
const network = WalletUtilities.getNetworkByType(wallets[0].networkType);
@@ -679,8 +767,10 @@ function* refreshWalletsWorker({
WalletOperations.syncWalletsViaElectrumClient,
wallets,
network,
- options.hardRefresh
+ options.hardRefresh,
+ assertCurrentScope
);
+ assertCurrentScope();
let labels: { ref: string; label: string; isSystem: boolean }[];
@@ -688,6 +778,15 @@ function* refreshWalletsWorker({
labels = yield call(dbManager.getCollection, RealmSchema.Tags);
}
for (const synchedWalletWithUTXOs of synchedWallets) {
+ const currentScope = yield select((state: RootState) => ({
+ appId: state.storage.appId,
+ networkType: state.settings.bitcoinNetworkType,
+ }));
+ if (
+ currentScope.appId !== refreshScope.appId ||
+ currentScope.networkType !== refreshScope.networkType
+ )
+ return false;
const { synchedWallet } = synchedWalletWithUTXOs;
if (!synchedWallet.specs.hasNewUpdates && !options.hardRefresh) continue; // no new updates found
@@ -707,9 +806,18 @@ function* refreshWalletsWorker({
);
}
- yield fork(bulkUpdateLabelsWorker, {
- payload: { labelChanges, UTXO: utxo, wallet: synchedWallet as any },
- });
+ if (labelChanges.added.length || labelChanges.deleted.length) {
+ assertCurrentScope();
+ yield call(bulkUpdateLabelsWorker, {
+ payload: {
+ labelChanges,
+ UTXO: utxo,
+ wallet: synchedWallet as any,
+ scope: refreshScope,
+ },
+ });
+ assertCurrentScope();
+ }
if (options.addNotifications) {
if (synchedWallet.type !== VaultType.CANARY) {
@@ -767,6 +875,7 @@ function* refreshWalletsWorker({
if (txsMissingOutputs.length > 0) {
const txidsToFetch = txsMissingOutputs.map((tx: any) => tx.txid);
try {
+ assertCurrentScope();
const rawTxs: Record = yield call(
[ElectrumClient, ElectrumClient.getTransactionsById],
txidsToFetch
@@ -869,20 +978,33 @@ function* refreshWalletsWorker({
}
// Write updated specs (with spendability) back to Realm
- const persisted = yield call(
- dbManager.updateObjectById,
- synchedWallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet,
- synchedWallet.id,
- { specs: synchedWallet.specs }
- );
+ const writeScope = yield select((state: RootState) => ({
+ appId: state.storage.appId,
+ networkType: state.settings.bitcoinNetworkType,
+ }));
+ if (
+ writeScope.appId !== refreshScope.appId ||
+ writeScope.networkType !== refreshScope.networkType
+ )
+ return false;
+ const persisted = yield call(() => {
+ assertCurrentScope();
+ return dbManager.updateObjectById(
+ synchedWallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet,
+ synchedWallet.id,
+ { specs: synchedWallet.specs }
+ );
+ });
if (!persisted) throw new Error('Failed to persist refreshed wallet');
if (options.addNotifications && newDustUTXOs.length > 0) {
yield put(setPendingDustToast(synchedWallet.id));
}
} // end for (synchedWalletWithUTXOs)
+ succeeded = true;
return true;
} catch (err) {
+ if (err?.message === WALLET_SYNC_SCOPE_CHANGED) return false;
if ([ELECTRUM_NOT_CONNECTED_ERR, ELECTRUM_NOT_CONNECTED_ERR_TOR].includes(err?.message)) {
yield put(
setElectrumNotConnectedErr(
@@ -899,7 +1021,11 @@ function* refreshWalletsWorker({
}
return false;
} finally {
- yield put(setSyncing({ wallets, isSyncing: false }));
+ if (lease?.owner) {
+ yield put(setSyncing({ wallets, isSyncing: false }));
+ lease.complete(succeeded);
+ }
+ if (requestId) yield put(finishRefreshRequest({ requestId, succeeded }));
}
}
@@ -913,46 +1039,101 @@ export function* autoWalletsSyncWorker({
hardRefresh?: boolean;
addNotifications?: boolean;
backupCheckAppId?: string;
+ archivedOnly?: boolean;
+ requestId?: string;
};
}) {
- const { syncAll, hardRefresh, addNotifications, backupCheckAppId } = payload;
- const wallets: Wallet[] = yield call(dbManager.getObjectByIndex, RealmSchema.Wallet, null, true);
- const vaults: Vault[] = yield call(dbManager.getObjectByIndex, RealmSchema.Vault, null, true);
- const { bitcoinNetworkType } = yield select((state: RootState) => state.settings);
-
- let walletsToSync: (Wallet | Vault)[] = [];
- for (const wallet of [...wallets, ...vaults]) {
- if (syncAll || wallet.presentationData.visibility === VisibilityType.DEFAULT) {
- if (wallet.entityKind === EntityKind.VAULT && (wallet as Vault).archived) continue;
- walletsToSync.push(getJSONFromRealmObject(wallet));
+ const { syncAll, hardRefresh, addNotifications, backupCheckAppId, archivedOnly, requestId } =
+ payload;
+ let activeSucceeded = true;
+ let archivedSucceeded = true;
+ try {
+ const syncScope = yield select((state: RootState) => ({
+ appId: state.storage.appId,
+ networkType: state.settings.bitcoinNetworkType,
+ }));
+ const wallets: Wallet[] = yield call(
+ dbManager.getObjectByIndex,
+ RealmSchema.Wallet,
+ null,
+ true
+ );
+ const vaults: Vault[] = yield call(dbManager.getObjectByIndex, RealmSchema.Vault, null, true);
+ const currentAppId = yield select((state: RootState) => state.storage.appId);
+ const currentNetworkType = yield select(
+ (state: RootState) => state.settings.bitcoinNetworkType
+ );
+ if (currentAppId !== syncScope.appId || currentNetworkType !== syncScope.networkType) {
+ activeSucceeded = false;
+ archivedSucceeded = false;
+ return;
}
- }
- walletsToSync = walletsToSync.filter((wallet) => wallet.networkType === bitcoinNetworkType);
+ const { active, archived } = selectWalletsForSync(
+ wallets || [],
+ vaults || [],
+ syncScope.networkType,
+ { syncAll, archivedOnly }
+ );
- let refreshSucceeded = true;
- if (walletsToSync.length) {
- refreshSucceeded = yield call(refreshWalletsWorker, {
- payload: {
- wallets: walletsToSync,
- options: {
- hardRefresh,
- addNotifications,
+ if (active.length) {
+ activeSucceeded = yield call(refreshWalletsWorker, {
+ payload: {
+ wallets: active.map(getJSONFromRealmObject),
+ options: { hardRefresh, addNotifications },
},
- },
- });
- }
- // Check backup freshness only after the refreshed wallet specs are persisted.
- // A failed refresh or account switch must not verify a stale snapshot.
- if (backupCheckAppId && refreshSucceeded) {
- const { appId } = yield select((state: RootState) => state.storage);
- const { automaticCloudBackup, pendingAllBackup, backupRepairCompletedByAppId = {} } =
- yield select((state: RootState) => state.bhr);
+ });
+ }
+ const beforeArchive = yield select((state: RootState) => ({
+ appId: state.storage.appId,
+ networkType: state.settings.bitcoinNetworkType,
+ }));
if (
- appId === backupCheckAppId &&
- automaticCloudBackup &&
- (pendingAllBackup || !backupRepairCompletedByAppId[appId])
+ beforeArchive.appId !== syncScope.appId ||
+ beforeArchive.networkType !== syncScope.networkType
) {
- yield put(checkBackupFreshness());
+ activeSucceeded = false;
+ archivedSucceeded = false;
+ return;
+ }
+ // Retained archived vaults are checked even when empty or hidden. Their
+ // transactions are persisted, while notification and transfer UX belongs to R09.
+ if (archived.length) {
+ archivedSucceeded = yield call(refreshWalletsWorker, {
+ payload: {
+ wallets: archived.map(getJSONFromRealmObject),
+ options: { hardRefresh, addNotifications: false },
+ },
+ });
+ }
+
+ // Check backup freshness only after the active wallet specs are persisted.
+ if (backupCheckAppId && activeSucceeded) {
+ const { appId } = yield select((state: RootState) => state.storage);
+ const {
+ automaticCloudBackup,
+ pendingAllBackup,
+ backupRepairCompletedByAppId = {},
+ } = yield select((state: RootState) => state.bhr);
+ if (
+ appId === backupCheckAppId &&
+ automaticCloudBackup &&
+ (pendingAllBackup || !backupRepairCompletedByAppId[appId])
+ ) {
+ yield put(checkBackupFreshness());
+ }
+ }
+ } catch (err) {
+ activeSucceeded = false;
+ archivedSucceeded = false;
+ captureError(err);
+ } finally {
+ if (requestId) {
+ yield put(
+ finishRefreshRequest({
+ requestId,
+ succeeded: activeSucceeded && archivedSucceeded,
+ })
+ );
}
}
}
@@ -1027,27 +1208,130 @@ export const updateSignerPolicyWatcher = createWatcher(
UPDATE_SIGNER_POLICY
);
-function* testcoinsWorker({ payload }) {
- const { wallet } = payload;
- const receivingAddress = WalletOperations.getNextFreeAddress(wallet);
- const network = WalletUtilities.getNetworkByType(wallet.networkType);
- const appId: string = yield select((state: RootState) => state.storage.appId);
+export function* testcoinsWorker({ payload }) {
+ let { wallet } = payload;
+ const faucetScope = yield select((state: RootState) => ({
+ appId: state.storage.appId,
+ networkType: state.settings.bitcoinNetworkType,
+ }));
+ const isCurrentFaucetScope = () => {
+ const state = store.getState();
+ try {
+ const keeperApp = dbManager.getObjectByIndex(RealmSchema.KeeperApp) as unknown as KeeperApp;
+ return (
+ state.storage.appId === faucetScope.appId &&
+ state.settings.bitcoinNetworkType === faucetScope.networkType &&
+ faucetScope.networkType === wallet.networkType &&
+ keeperApp?.id === faucetScope.appId
+ );
+ } catch {
+ return false;
+ }
+ };
+
+ if (!isCurrentFaucetScope()) return;
+ const currentWallet = yield call(() => {
+ if (!isCurrentFaucetScope()) return null;
+ const schema = wallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet;
+ const stored = dbManager.getObjectById(schema, wallet.id);
+ if (
+ !stored ||
+ stored.networkType !== wallet.networkType ||
+ stored.entityKind !== wallet.entityKind
+ )
+ return null;
+ return getJSONFromRealmObject(stored);
+ });
+ if (!currentWallet || !isCurrentFaucetScope()) return;
+ wallet = currentWallet;
+ yield put(setTestCoinsReceived(false));
+ yield put(setTestCoinsFailed(false));
+ yield put(setTestCoinsPending(null));
+
+ if (wallet.networkType !== NetworkType.TESTNET) {
+ yield put(setTestCoinsFailed(true));
+ return;
+ }
+ let receivingAddress: string;
+ let network: ReturnType;
+ let txid: string;
try {
- const { txid } = yield call(Relay.getTestcoins, receivingAddress, network, appId);
- if (!txid) {
- yield put(setTestCoinsFailed(true));
- } else {
- yield put(setTestCoinsReceived(true));
- yield put(refreshWallets([wallet], { hardRefresh: true }));
- }
+ receivingAddress = WalletOperations.getNextFreeAddress(wallet);
+ network = WalletUtilities.getNetworkByType(wallet.networkType);
+ const response = yield call(() => {
+ if (!isCurrentFaucetScope()) return null;
+ return Relay.getTestcoins(receivingAddress, wallet.networkType, faucetScope.appId);
+ });
+ if (!response) return;
+ txid = response.txid;
} catch (err) {
+ if (!isCurrentFaucetScope()) return;
if (err.message === 'FAUCET_DAILY_LIMIT_REACHED') {
yield put(setTestCoinsQuotaReached(true));
+ } else if (err.message === 'FAUCET_OUTCOME_UNKNOWN') {
+ yield put(setTestCoinsPending('unknown'));
} else {
yield put(setTestCoinsFailed(true));
}
+ return;
+ }
+
+ if (!isCurrentFaucetScope()) return;
+
+ let lastAttemptSynced = false;
+ for (let attempt = 0; attempt < 8; attempt += 1) {
+ let attemptSynced = false;
+ try {
+ if (!isCurrentFaucetScope()) return;
+ let connectionMatchesScope = false;
+ try {
+ ElectrumClient.assertConnectionGeneration(
+ ElectrumClient.getConnectionGeneration(),
+ wallet.networkType
+ );
+ connectionMatchesScope = true;
+ } catch {
+ // The old profile or network's connection must not be reused.
+ }
+ if (!ELECTRUM_CLIENT.isClientConnected || !connectionMatchesScope) {
+ yield call(connectToNodeWorker);
+ }
+ if (!isCurrentFaucetScope()) return;
+ const connectionGeneration = ElectrumClient.getConnectionGeneration();
+ ElectrumClient.assertConnectionGeneration(connectionGeneration, wallet.networkType);
+ const { txids } = yield call(
+ [ElectrumClient, ElectrumClient.syncHistoryByAddress],
+ [receivingAddress],
+ network
+ );
+ ElectrumClient.assertConnectionGeneration(connectionGeneration, wallet.networkType);
+ if (!isCurrentFaucetScope()) return;
+ attemptSynced = true;
+ if (txids.some((seenTxid: string) => seenTxid.toLowerCase() === txid.toLowerCase())) {
+ const refreshed = yield call(refreshWalletsWorker, {
+ payload: { wallets: [wallet], options: { hardRefresh: true } },
+ });
+ if (refreshed) {
+ const schema =
+ wallet.entityKind === EntityKind.VAULT ? RealmSchema.Vault : RealmSchema.Wallet;
+ const storedWallet = yield call(dbManager.getObjectById, schema, wallet.id);
+ const storedData = storedWallet?.toJSON?.() || storedWallet;
+ if (isFaucetTxVisible(storedData, txid)) {
+ if (!isCurrentFaucetScope()) return;
+ yield put(setTestCoinsReceived(true));
+ return;
+ }
+ } else attemptSynced = false;
+ }
+ } catch (err) {
+ attemptSynced = false;
+ }
+ lastAttemptSynced = attemptSynced;
+ if (attempt < 7) yield delay(4000);
}
+ if (!isCurrentFaucetScope()) return;
+ yield put(setTestCoinsPending(lastAttemptSynced ? 'propagation' : 'sync'));
}
export const testcoinsWatcher = createWatcher(testcoinsWorker, TEST_SATS_RECIEVE);
diff --git a/src/utils/helpAiChatBehavior.ts b/src/utils/helpAiChatBehavior.ts
new file mode 100644
index 0000000000..caa67bf999
--- /dev/null
+++ b/src/utils/helpAiChatBehavior.ts
@@ -0,0 +1,33 @@
+export const HELP_AI_NEAR_BOTTOM_DISTANCE = 80;
+
+export const isNearChatBottom = (
+ offsetY: number,
+ viewportHeight: number,
+ contentHeight: number
+): boolean => contentHeight - offsetY - viewportHeight <= HELP_AI_NEAR_BOTTOM_DISTANCE;
+
+export const findRetryableChatMessage = (
+ messages: Array<{ id: string; type: string; text?: string }>,
+ failedMessageId?: string | null
+): { id: string; text: string } | undefined => {
+ if (!failedMessageId) return undefined;
+ const message = messages.find((item) => item.id === failedMessageId);
+ return message?.type === 'user' && typeof message.text === 'string'
+ ? { id: message.id, text: message.text }
+ : undefined;
+};
+
+export const canSendChatMessage = (
+ failedMessageId?: string | null,
+ retryMessageId?: string
+): boolean => !failedMessageId || failedMessageId === retryMessageId;
+
+export const removeFailedChatMessage = (
+ messages: T[],
+ failedMessageId: string
+): T[] => messages.filter((message) => message.id !== failedMessageId);
+
+export const planChatSend = (input: string, retryMessage?: { text: string }) => ({
+ outboundText: retryMessage ? retryMessage.text : input.trim(),
+ appendUserMessage: !retryMessage,
+});
diff --git a/tests/helpAiChatBehavior.test.ts b/tests/helpAiChatBehavior.test.ts
new file mode 100644
index 0000000000..20712e7b82
--- /dev/null
+++ b/tests/helpAiChatBehavior.test.ts
@@ -0,0 +1,61 @@
+import {
+ canSendChatMessage,
+ findRetryableChatMessage,
+ isNearChatBottom,
+ planChatSend,
+ removeFailedChatMessage,
+} from '../src/utils/helpAiChatBehavior';
+
+test('new content follows only while the reader is near the bottom', () => {
+ expect(isNearChatBottom(200, 400, 680)).toBe(true);
+ expect(isNearChatBottom(199, 400, 680)).toBe(false);
+ expect(isNearChatBottom(0, 400, 200)).toBe(true);
+});
+
+test('a fresh send adds one user message with trimmed text', () => {
+ expect(planChatSend(' How do I reconnect? ')).toEqual({
+ outboundText: 'How do I reconnect?',
+ appendUserMessage: true,
+ });
+});
+
+test('retry resends the failed message without adding a second user bubble', () => {
+ const threadAfterReturn: {
+ failedMessageId: string;
+ messages: Array<{ id: string; type: string; text: string }>;
+ } = JSON.parse(
+ JSON.stringify({
+ failedMessageId: 'failed-1',
+ messages: [
+ { id: 'failed-1', type: 'user', text: 'Original failed message' },
+ { id: 'ai-1', type: 'ai', text: 'Earlier answer' },
+ ],
+ })
+ );
+ const failedMessage = findRetryableChatMessage(
+ threadAfterReturn.messages,
+ threadAfterReturn.failedMessageId
+ );
+ expect(failedMessage).toEqual({ id: 'failed-1', text: 'Original failed message' });
+ expect(planChatSend('draft typed after failure', failedMessage)).toEqual({
+ outboundText: 'Original failed message',
+ appendUserMessage: false,
+ });
+ expect(findRetryableChatMessage(threadAfterReturn.messages, 'ai-1')).toBeUndefined();
+});
+
+test('a failed bubble must be retried or discarded before sending a different message', () => {
+ const messages = [
+ { id: 'question-1', type: 'user', text: 'First question' },
+ { id: 'reply-1', type: 'ai', text: 'First answer' },
+ { id: 'failed-1', type: 'user', text: 'Unsent question' },
+ ];
+
+ expect(canSendChatMessage('failed-1')).toBe(false);
+ expect(canSendChatMessage('failed-1', 'failed-1')).toBe(true);
+ expect(canSendChatMessage('failed-1', 'question-1')).toBe(false);
+
+ const afterDiscard = removeFailedChatMessage(messages, 'failed-1');
+ expect(afterDiscard.map((message) => message.id)).toEqual(['question-1', 'reply-1']);
+ expect(canSendChatMessage(null)).toBe(true);
+});
diff --git a/tests/hooks/walletCollectionMemo.test.tsx b/tests/hooks/walletCollectionMemo.test.tsx
new file mode 100644
index 0000000000..d66a3c4bfa
--- /dev/null
+++ b/tests/hooks/walletCollectionMemo.test.tsx
@@ -0,0 +1,169 @@
+import React from 'react';
+import TestRenderer, { act } from 'react-test-renderer';
+import { useObject, useQuery } from '@realm/react';
+import { useAppSelector } from 'src/store/hooks';
+import useWallets from 'src/hooks/useWallets';
+import useVault from 'src/hooks/useVault';
+import { RealmSchema } from 'src/storage/realm/enum';
+import { NetworkType, VaultType, VisibilityType, WalletType } from 'src/services/wallets/enums';
+
+jest.mock('src/store/hooks', () => ({ useAppSelector: jest.fn() }));
+
+const queryMock = useQuery as jest.Mock;
+const objectMock = useObject as jest.Mock;
+const selectorMock = useAppSelector as jest.Mock;
+
+const makeManaged = (id: string, overrides: Record = {}) => {
+ const value = {
+ id,
+ type: WalletType.DEFAULT,
+ networkType: NetworkType.MAINNET,
+ archived: false,
+ presentationData: { name: id, visibility: VisibilityType.DEFAULT },
+ specs: { balances: { confirmed: 100, unconfirmed: 0 } },
+ ...overrides,
+ };
+ return { ...value, toJSON: jest.fn(() => ({ ...value })) };
+};
+
+describe('wallet and Vault list snapshots', () => {
+ let network: NetworkType;
+ let wallets: any[];
+ let vaults: any[];
+
+ beforeEach(() => {
+ network = NetworkType.MAINNET;
+ wallets = [];
+ vaults = [];
+ queryMock.mockImplementation((schema) => (schema === RealmSchema.Wallet ? wallets : vaults));
+ objectMock.mockReset();
+ selectorMock.mockImplementation((selector) =>
+ selector({ settings: { bitcoinNetworkType: network } })
+ );
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ test('wallets convert only selected network objects and refresh on query or network change', () => {
+ const main = makeManaged('main');
+ const otherNetwork = makeManaged('testnet', { networkType: NetworkType.TESTNET });
+ const hidden = makeManaged('hidden', {
+ presentationData: { name: 'hidden', visibility: VisibilityType.HIDDEN },
+ });
+ const legacy = makeManaged('legacy', { type: WalletType.PRE_MIX });
+ wallets = [main, otherNetwork, hidden, legacy];
+ let seen: any[] = [];
+ const Probe = ({ getAll = false, tick = 0 }) => {
+ seen = useWallets({ getAll }).wallets;
+ return <>{tick}>;
+ };
+ let tree: TestRenderer.ReactTestRenderer;
+ act(() => {
+ tree = TestRenderer.create();
+ });
+ expect(seen.map((wallet) => wallet.id)).toEqual(['main']);
+ expect(main.toJSON).toHaveBeenCalledTimes(1);
+ expect(otherNetwork.toJSON).not.toHaveBeenCalled();
+ expect(hidden.toJSON).not.toHaveBeenCalled();
+ act(() => tree.update());
+ expect(main.toJSON).toHaveBeenCalledTimes(1);
+
+ act(() => tree.update());
+ expect(seen.map((wallet) => wallet.id)).toEqual(['main', 'hidden']);
+ expect(hidden.toJSON).toHaveBeenCalledTimes(1);
+
+ const changed = makeManaged('main', {
+ specs: { balances: { confirmed: 250, unconfirmed: 0 } },
+ });
+ wallets = [changed, otherNetwork, hidden, legacy];
+ act(() => tree.update());
+ expect(seen[0].specs.balances.confirmed).toBe(250);
+ expect(changed.toJSON).toHaveBeenCalledTimes(1);
+
+ network = NetworkType.TESTNET;
+ act(() => tree.update());
+ expect(seen.map((wallet) => wallet.id)).toEqual(['testnet']);
+ expect(otherNetwork.toJSON).toHaveBeenCalledTimes(1);
+ act(() => tree.unmount());
+ });
+
+ test('Vaults preserve archived, hidden and canary selection while avoiding unrelated conversions', () => {
+ const active = makeManaged('active');
+ const archived = makeManaged('archive', {
+ archived: true,
+ specs: { balances: { confirmed: 0, unconfirmed: 0 } },
+ });
+ const hidden = makeManaged('hidden', {
+ presentationData: { name: 'hidden', visibility: VisibilityType.HIDDEN },
+ });
+ const canary = makeManaged('canary', { type: VaultType.CANARY });
+ const otherNetwork = makeManaged('testnet', { networkType: NetworkType.TESTNET });
+ vaults = [active, archived, hidden, canary, otherNetwork];
+ let seen: ReturnType;
+ const Probe = ({ tick = 0, includeArchived = false, vaultId = '' }) => {
+ seen = useVault({ includeArchived, getHiddenWallets: false, vaultId });
+ return <>{tick}>;
+ };
+ let tree: TestRenderer.ReactTestRenderer;
+ act(() => {
+ tree = TestRenderer.create();
+ });
+ expect(seen.allVaults.map((vault) => vault.id)).toEqual(['active']);
+ expect(active.toJSON).toHaveBeenCalledTimes(1);
+ expect(archived.toJSON).not.toHaveBeenCalled();
+ expect(otherNetwork.toJSON).not.toHaveBeenCalled();
+ act(() => tree.update());
+ expect(active.toJSON).toHaveBeenCalledTimes(1);
+
+ act(() => tree.update());
+ expect(seen.activeVault?.id).toBe('canary');
+ expect(canary.toJSON).toHaveBeenCalledTimes(1);
+ expect(active.toJSON).toHaveBeenCalledTimes(1);
+
+ act(() => tree.update());
+ expect(seen.activeVault?.id).toBe('archive');
+ expect(seen.allVaults.map((vault) => vault.id)).toEqual(['active', 'archive']);
+ expect((seen.activeVault as any)?.specs.balances.confirmed).toBe(0);
+ const updatedArchive = makeManaged('archive', {
+ archived: true,
+ specs: { balances: { confirmed: 50, unconfirmed: 0 } },
+ });
+ vaults = [active, updatedArchive, hidden, canary, otherNetwork];
+ act(() => tree.update());
+ expect((seen.activeVault as any)?.specs.balances.confirmed).toBe(50);
+ act(() => tree.unmount());
+ });
+
+ test('ID selection keeps order and survives an empty-to-populated route update', () => {
+ const first = makeManaged('first');
+ const hidden = makeManaged('hidden', {
+ presentationData: { name: 'hidden', visibility: VisibilityType.HIDDEN },
+ });
+ wallets = [first, hidden];
+ let seen: any[] = [];
+ const Probe = ({ walletIds = [] }: { walletIds?: string[] }) => {
+ seen = useWallets({ walletIds }).wallets;
+ return null;
+ };
+ let tree: TestRenderer.ReactTestRenderer;
+ act(() => {
+ tree = TestRenderer.create();
+ });
+ expect(seen.map((wallet) => wallet.id)).toEqual(['first']);
+
+ act(() => tree.update());
+ expect(seen.map((wallet) => wallet.id)).toEqual(['hidden', 'first', 'hidden']);
+ expect(hidden.toJSON).toHaveBeenCalledTimes(2);
+ act(() => tree.update());
+ expect(hidden.toJSON).toHaveBeenCalledTimes(2);
+
+ network = undefined as any;
+ act(() => tree.update());
+ expect(seen[0]).toBe(hidden);
+ act(() => tree.update());
+ expect(seen.map((wallet) => wallet.id)).toEqual(['first']);
+ act(() => tree.unmount());
+ });
+});
diff --git a/tests/navigation/remoteKeyDeepLink.test.mjs b/tests/navigation/remoteKeyDeepLink.test.mjs
new file mode 100644
index 0000000000..32819da7e4
--- /dev/null
+++ b/tests/navigation/remoteKeyDeepLink.test.mjs
@@ -0,0 +1,36 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { getRemoteKeyFromDeepLink } from '../../src/navigation/remoteKeyDeepLink.ts';
+
+const key = '0123456789abcdef01234567';
+
+test('accepts generated production and development remote-key exchange links', () => {
+ assert.equal(
+ getRemoteKeyFromDeepLink(`https://www.bitcoinkeeper.app/app/prod/remote/${key}`, 'PRODUCTION'),
+ key
+ );
+ assert.equal(
+ getRemoteKeyFromDeepLink(`https://bitcoinkeeper.app/app/dev/remote/${key}`, 'DEVELOPMENT'),
+ key
+ );
+ assert.equal(
+ getRemoteKeyFromDeepLink(`https://www.bitcoinkeeper.app/app/prod/remote/${key}?source=share`, 'PRODUCTION'),
+ key
+ );
+});
+
+test('rejects a different stage, site, route, or malformed encryption key before fetching', () => {
+ for (const url of [
+ `https://www.bitcoinkeeper.app/app/dev/remote/${key}`,
+ `https://bitcoinkeeper.app.evil.test/app/prod/remote/${key}`,
+ `http://www.bitcoinkeeper.app/app/prod/remote/${key}`,
+ `https://www.bitcoinkeeper.app.evil.test/app/prod/remote/${key}`,
+ `https://www.bitcoinkeeper.app/app/prod/remote/${key}/extra`,
+ `https://www.bitcoinkeeper.app/app/prod/remote/${key.toUpperCase()}`,
+ `https://www.bitcoinkeeper.app/app/prod/remote/${key.slice(0, -1)}`,
+ `https://www.bitcoinkeeper.app/app/prod/remote/${key}zz`,
+ 'not a link',
+ ]) {
+ assert.equal(getRemoteKeyFromDeepLink(url, 'PRODUCTION'), null, url);
+ }
+});
diff --git a/tests/recovery/backupFreshness.test.cjs b/tests/recovery/backupFreshness.test.cjs
index 4676654e7c..2f5a32c5c0 100644
--- a/tests/recovery/backupFreshness.test.cjs
+++ b/tests/recovery/backupFreshness.test.cjs
@@ -5,6 +5,35 @@ const ts = require('typescript');
const { fixture, enums, encryption, wallet, loadModule, functions } = require('./sagaHarness.cjs');
const { NetworkType, WalletType } = enums;
+test('archived-only resume keeps checking an empty hidden vault without notifications', async () => {
+ const f = fixture();
+ f.collections.Wallet.push(wallet('visible-wallet', NetworkType.MAINNET));
+ f.collections.Vault.push({
+ ...wallet('empty-archive', NetworkType.MAINNET),
+ entityKind: enums.EntityKind.VAULT,
+ archived: true,
+ presentationData: { visibility: 'HIDDEN' },
+ specs: { balances: { confirmed: 0, unconfirmed: 0 } },
+ });
+ f.collections.Vault.push({
+ ...wallet('other-network-archive', NetworkType.TESTNET),
+ entityKind: enums.EntityKind.VAULT,
+ archived: true,
+ });
+ const batches = [];
+ f.scope.refreshWalletsWorker = async ({ payload }) => {
+ batches.push(payload);
+ return true;
+ };
+
+ await f.run('autoWalletsSyncWorker', { payload: { archivedOnly: true } });
+ await f.run('autoWalletsSyncWorker', { payload: { archivedOnly: true } });
+ assert.deepEqual(batches.map(({ wallets }) => wallets.map(({ id }) => id)), [
+ ['empty-archive'], ['empty-archive'],
+ ]);
+ assert.ok(batches.every(({ options }) => options.addNotifications === false));
+});
+
function refreshFixture(kind, rejectWrite = false) {
const f = fixture({ bhr: { pendingAllBackup: true } });
const original = {
@@ -18,7 +47,20 @@ function refreshFixture(kind, rejectWrite = false) {
};
f.collections[kind].push(original);
f.scope.getJSONFromRealmObject = (value) => JSON.parse(JSON.stringify(value));
- f.scope.ELECTRUM_CLIENT = { isClientConnected: true };
+ f.scope.WALLET_SYNC_SCOPE_CHANGED = 'WALLET_SYNC_SCOPE_CHANGED';
+ f.scope.store = { getState: () => f.state };
+ f.scope.ELECTRUM_CLIENT = {
+ isClientConnected: true,
+ activePeer: { networkType: NetworkType.MAINNET },
+ };
+ f.scope.ElectrumClient = {
+ getConnectionGeneration: () => 1,
+ assertConnectionGeneration: (_generation, networkType) => {
+ if (networkType !== f.scope.ELECTRUM_CLIENT.activePeer.networkType) {
+ throw new Error('Electrum network changed');
+ }
+ },
+ };
f.scope.WalletUtilities.getNetworkByType = () => ({});
f.scope.WalletOperations = { syncWalletsViaElectrumClient: async () => {
const synced = f.scope.getJSONFromRealmObject(original);
@@ -52,7 +94,7 @@ for (const kind of ['Wallet', 'Vault']) {
test(`${kind}: rejected refresh persistence returns failure and clears syncing`, async () => {
const f = refreshFixture(kind, true);
assert.equal(await f.run('refreshWalletsWorker', {
- payload: { wallets: f.collections[kind], options: { hardRefresh: true } },
+ payload: { wallets: f.collections[kind], options: { hardRefresh: true }, requestId: 'failed-pull' },
}), false);
assert.deepEqual(f.writes, [kind]);
assert.equal(f.collections[kind][0].specs.receivingAddress, 'before-refresh');
@@ -61,6 +103,9 @@ for (const kind of ['Wallet', 'Vault']) {
assert.equal(f.errors.length, 1);
assert.ok(f.actions.some((action) => action.type === 'setElectrumNotConnectedErr' &&
action.payload.includes('Failed to persist refreshed wallet')));
+ const finished = f.actions.find((action) => action.type === 'finishRefreshRequest')?.payload;
+ assert.equal(finished?.requestId, 'failed-pull');
+ assert.equal(finished?.succeeded, false);
});
test(`${kind}: login never inspects stale specs after rejected refresh persistence`, async () => {
@@ -82,6 +127,48 @@ for (const kind of ['Wallet', 'Vault']) {
});
}
+test('successful pull refresh completes only after refreshed specs are persisted', async () => {
+ const f = refreshFixture('Wallet');
+ assert.equal(await f.run('refreshWalletsWorker', {
+ payload: { wallets: f.collections.Wallet, options: { hardRefresh: true }, requestId: 'saved-pull' },
+ }), true);
+ assert.equal(f.collections.Wallet[0].specs.receivingAddress, 'after-refresh');
+ const finished = f.actions.find((action) => action.type === 'finishRefreshRequest')?.payload;
+ assert.equal(finished?.requestId, 'saved-pull');
+ assert.equal(finished?.succeeded, true);
+});
+
+test('refresh does not read or write another Realm during account handover', async () => {
+ const f = refreshFixture('Wallet');
+ f.app.id = 'new-profile'; // Realm B opened while Redux still names account A.
+ assert.equal(await f.run('refreshWalletsWorker', {
+ payload: { wallets: f.collections.Wallet, options: { hardRefresh: true } },
+ }), false);
+ assert.deepEqual(f.writes, []);
+ assert.equal(f.collections.Wallet[0].specs.receivingAddress, 'before-refresh');
+ assert.deepEqual(f.errors, []);
+});
+
+test('manual refresh reports a disconnected current node and ends its request', async () => {
+ const f = refreshFixture('Wallet');
+ f.scope.ELECTRUM_CLIENT.isClientConnected = false;
+ f.scope.ElectrumClient.resetCurrentPeerIndex = () => {};
+ f.scope.connectToNodeWorker = () => {};
+ assert.equal(await f.run('refreshWalletsWorker', {
+ payload: {
+ wallets: f.collections.Wallet,
+ options: { hardRefresh: true },
+ requestId: 'disconnected-pull',
+ },
+ }), false);
+ assert.deepEqual(f.writes, []);
+ assert.ok(f.actions.some((action) =>
+ action.type === 'setElectrumNotConnectedErr' && action.payload.includes('Network error')));
+ const finished = f.actions.find((action) => action.type === 'finishRefreshRequest')?.payload;
+ assert.equal(finished?.requestId, 'disconnected-pull');
+ assert.equal(finished?.succeeded, false);
+});
+
test('login backup inspection waits for wallet refresh to finish', async () => {
let finishSync;
const syncGate = new Promise((resolve) => { finishSync = resolve; });
diff --git a/tests/recovery/faucetVisibilityAcceptance.test.cjs b/tests/recovery/faucetVisibilityAcceptance.test.cjs
new file mode 100644
index 0000000000..bbe8e48d54
--- /dev/null
+++ b/tests/recovery/faucetVisibilityAcceptance.test.cjs
@@ -0,0 +1,123 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const vm = require('node:vm');
+const ts = require('typescript');
+const { fixture, enums, wallet, loadModule, functions } = require('./sagaHarness.cjs');
+
+const txid = 'a'.repeat(64);
+
+function faucetFixture(balanceOnAttempt) {
+ const f = fixture();
+ f.state.settings.bitcoinNetworkType = enums.NetworkType.TESTNET;
+ f.app.networkType = enums.NetworkType.TESTNET;
+ const stored = {
+ ...wallet('disposable-faucet', enums.NetworkType.TESTNET),
+ specs: {
+ balances: { confirmed: 0, unconfirmed: 0 },
+ confirmedUTXOs: [],
+ unconfirmedUTXOs: [],
+ addresses: { external: {}, internal: {} },
+ transactions: [],
+ receivingAddress: 'tb1qdisposable',
+ },
+ };
+ f.collections.Wallet.push(stored);
+
+ f.scope.getJSONFromRealmObject = (value) => JSON.parse(JSON.stringify(value));
+ f.scope.store = { getState: () => f.state };
+ f.scope.WALLET_SYNC_SCOPE_CHANGED = 'WALLET_SYNC_SCOPE_CHANGED';
+ f.scope.ELECTRUM_CLIENT = {
+ isClientConnected: true,
+ activePeer: { networkType: enums.NetworkType.TESTNET },
+ };
+ let historyPolls = 0;
+ f.scope.ElectrumClient = {
+ getConnectionGeneration: () => 1,
+ assertConnectionGeneration: (_generation, network) => {
+ assert.equal(network, enums.NetworkType.TESTNET);
+ },
+ syncHistoryByAddress: async () => {
+ historyPolls += 1;
+ return { txids: [txid] };
+ },
+ };
+ f.scope.WalletUtilities.getNetworkByType = () => ({ network: 'testnet4' });
+ let refreshes = 0;
+ f.scope.WalletOperations = {
+ getNextFreeAddress: () => stored.specs.receivingAddress,
+ syncWalletsViaElectrumClient: async (wallets) => {
+ refreshes += 1;
+ const synced = f.scope.getJSONFromRealmObject(wallets[0]);
+ synced.specs.unconfirmedUTXOs = [{
+ txId: txid,
+ vout: 0,
+ address: stored.specs.receivingAddress,
+ value: 1000,
+ }];
+ synced.specs.balances = { confirmed: 0, unconfirmed: balanceOnAttempt(refreshes) };
+ synced.specs.hasNewUpdates = true;
+ return { synchedWallets: [{ synchedWallet: synced, newUTXOs: [] }] };
+ },
+ };
+ let relayRequests = 0;
+ f.scope.Relay.getTestcoins = async () => {
+ relayRequests += 1;
+ return { txid, funded: true };
+ };
+ f.scope.isFaucetTxVisible = loadModule('src/store/sagas/faucetVisibility.ts').isFaucetTxVisible;
+ f.scope.classifyDustByAddress = () => ({
+ taintedAddresses: new Set(), initialTaintAddresses: new Set(), dustSpendTxids: new Set(),
+ });
+ for (const name of [
+ 'setTestCoinsReceived', 'setTestCoinsFailed', 'setTestCoinsPending',
+ 'setTestCoinsQuotaReached', 'setSyncing', 'setElectrumNotConnectedErr',
+ ]) {
+ f.scope[name] = (payload) => ({ type: name, payload });
+ }
+ f.scope.ELECTRUM_NOT_CONNECTED_ERR = 'offline';
+ f.scope.ELECTRUM_NOT_CONNECTED_ERR_TOR = 'tor-offline';
+ f.scope.delay = () => Promise.resolve();
+
+ const writes = [];
+ const originalUpdate = f.scope.dbManager.updateObjectById;
+ f.scope.dbManager.updateObjectById = (schema, id, patch) => {
+ writes.push({ schema, balance: patch.specs.balances.unconfirmed });
+ return originalUpdate(schema, id, patch);
+ };
+ vm.runInNewContext(ts.transpileModule(
+ functions('src/store/sagas/wallets.ts', ['refreshWalletsWorker', 'testcoinsWorker']),
+ { compilerOptions: { target: ts.ScriptTarget.ES2020 } }
+ ).outputText, f.scope);
+
+ return {
+ f, stored, writes,
+ getCounts: () => ({ relayRequests, historyPolls, refreshes }),
+ };
+}
+
+test('faucet receipt waits for a funded UTXO and Home-visible persisted balance', async () => {
+ const { f, stored, writes, getCounts } = faucetFixture((attempt) => attempt === 1 ? 0 : 1000);
+ await f.run('testcoinsWorker', { payload: { wallet: stored } });
+
+ assert.deepEqual(getCounts(), { relayRequests: 1, historyPolls: 2, refreshes: 2 });
+ assert.deepEqual(writes, [
+ { schema: 'Wallet', balance: 0 },
+ { schema: 'Wallet', balance: 1000 },
+ ]);
+ assert.deepEqual(f.actions.filter((action) => action.type === 'setTestCoinsReceived')
+ .map((action) => action.payload), [false, true]);
+ assert.equal(stored.specs.balances.unconfirmed, 1000);
+ assert.equal(stored.specs.unconfirmedUTXOs[0].txId, txid);
+});
+
+test('faucet reports pending when the funded txid persists but visible balance stays zero', async () => {
+ const { f, stored, writes, getCounts } = faucetFixture(() => 0);
+ await f.run('testcoinsWorker', { payload: { wallet: stored } });
+
+ assert.deepEqual(getCounts(), { relayRequests: 1, historyPolls: 8, refreshes: 8 });
+ assert.equal(writes.length, 8);
+ assert.equal(f.actions.some((action) =>
+ action.type === 'setTestCoinsReceived' && action.payload === true), false);
+ assert.ok(f.actions.some((action) =>
+ action.type === 'setTestCoinsPending' && action.payload === 'propagation'));
+});
diff --git a/tests/recovery/manualCoinChoices.test.cjs b/tests/recovery/manualCoinChoices.test.cjs
index 2f7a4ae47c..eed6e9368c 100644
--- a/tests/recovery/manualCoinChoices.test.cjs
+++ b/tests/recovery/manualCoinChoices.test.cjs
@@ -18,10 +18,17 @@ const withCoins = (kind = 'Wallet') => ({
specs: { confirmedUTXOs: [coin('spendable', { isManualOverride: false })],
unconfirmedUTXOs: [], transactions: [], addresses: { external: {}, internal: {} } },
});
-function loadFunctions(scope, file, names) {
+function loadFunctions(scope, file, names, constantNames = []) {
const source = ts.createSourceFile(file, fs.readFileSync(path.join(__dirname, '../..', file), 'utf8'), ts.ScriptTarget.Latest, true);
- const code = source.statements.filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text))
- .map(node => node.getText(source).replace(/^export /, '')).join('\n');
+ const constants = source.statements.filter(ts.isVariableStatement)
+ .flatMap(node => Array.from(node.declarationList.declarations))
+ .filter(node => ts.isIdentifier(node.name) && constantNames.includes(node.name.text));
+ assert.equal(constants.length, constantNames.length);
+ const code = [
+ ...constants.map(node => `const ${node.getText(source)};`),
+ ...source.statements.filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text))
+ .map(node => node.getText(source).replace(/^export /, '')),
+ ].join('\n');
assert.equal(source.statements.filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text)).length, names.length);
vm.runInNewContext(ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText, scope);
}
@@ -114,9 +121,23 @@ test('rejected local persistence never uploads an unapplied coin choice', async
for (const kind of ['Wallet', 'Vault']) for (const choice of ['doNotSpend', 'spendable']) test(`${kind}: restored manual ${choice} survives real refresh orchestration`, async () => {
const f = sagaFixture(); const restored = withCoins(kind); restored.specs.confirmedUTXOs = [coin(choice)];
f.collections[kind].push(restored);
- f.scope.ELECTRUM_CLIENT = { isClientConnected: true };
+ f.scope.store = { getState: () => f.state };
+ f.scope.ELECTRUM_CLIENT = { isClientConnected: true, activePeer: { networkType: enums.NetworkType.MAINNET } };
+ f.scope.ElectrumClient = {
+ getConnectionGeneration: () => 1,
+ assertConnectionGeneration: (generation, networkType) => {
+ assert.equal(generation, 1);
+ assert.equal(networkType, f.state.settings.bitcoinNetworkType);
+ assert.equal(networkType, f.scope.ELECTRUM_CLIENT.activePeer.networkType);
+ },
+ resetCurrentPeerIndex: () => { throw Error('Current fixture connection should not reconnect'); },
+ };
+ let syncCalls = 0, persistCalls = 0;
+ const persist = f.scope.dbManager.updateObjectById;
+ f.scope.dbManager.updateObjectById = (...args) => { persistCalls += 1; return persist(...args); };
f.scope.WalletUtilities.getNetworkByType = () => ({});
f.scope.WalletOperations = { syncWalletsViaElectrumClient: async () => {
+ syncCalls += 1;
const synced = clone(restored);
synced.specs.confirmedUTXOs = [coin('spendable', { isManualOverride: false })];
return { synchedWallets: [{ synchedWallet: synced, newUTXOs: [] }] };
@@ -129,8 +150,10 @@ for (const kind of ['Wallet', 'Vault']) for (const choice of ['doNotSpend', 'spe
f.scope.setSyncing = payload => ({ type: 'syncing', payload });
f.scope.setElectrumNotConnectedErr = error => { throw Error(error); };
f.scope.ELECTRUM_NOT_CONNECTED_ERR = 'offline'; f.scope.ELECTRUM_NOT_CONNECTED_ERR_TOR = 'tor-offline';
- loadFunctions(f.scope, 'src/store/sagas/wallets.ts', ['refreshWalletsWorker']);
- await f.run('refreshWalletsWorker', { payload: { wallets: [restored], options: { hardRefresh: true } } });
+ loadFunctions(f.scope, 'src/store/sagas/wallets.ts', ['refreshWalletsWorker'], ['WALLET_SYNC_SCOPE_CHANGED']);
+ assert.equal(await f.run('refreshWalletsWorker', { payload: { wallets: [restored], options: { hardRefresh: true } } }), true);
+ assert.equal(syncCalls, 1);
+ assert.equal(persistCalls, 1);
assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].spendability, choice);
assert.equal(f.collections[kind][0].specs.confirmedUTXOs[0].isManualOverride, true);
});
diff --git a/tests/recovery/sagaHarness.cjs b/tests/recovery/sagaHarness.cjs
index 37cc5412d7..a7a821f9f0 100644
--- a/tests/recovery/sagaHarness.cjs
+++ b/tests/recovery/sagaHarness.cjs
@@ -43,6 +43,8 @@ const encryption = loadModule('src/utils/service-utilities/encryption.ts', {
});
const { image } = require('./helpers.cjs');
const { prepareRecoveryImage } = loadModule('src/services/backup/restore.ts', { './image': image });
+const { selectWalletsForSync } = loadModule('src/store/sagas/walletSyncSelection.js');
+const { acquireWalletRefresh } = loadModule('src/store/sagas/walletRefreshCoordinator.js');
const account = loadModule('src/store/reducers/account.ts', {
'src/services/wallets/enums': enums,
'src/models/enums/BHR': loadModule('src/models/enums/BHR.ts'),
@@ -118,6 +120,9 @@ function fixture(options = {}) {
...encryption,
...enums,
...account,
+ selectWalletsForSync,
+ acquireWalletRefresh,
+ finishRefreshRequest: (payload) => ({ type: 'finishRefreshRequest', payload }),
prepareRecoveryImage,
pauseBackup: image.pauseBackup,
console: { log() {}, error() {} },
@@ -138,6 +143,7 @@ function fixture(options = {}) {
dbManager: {
getObjectByIndex: (schema, _index, all) =>
schema === 'KeeperApp' ? app : all ? collections[schema] : collections[schema]?.[0],
+ getObjectById: (schema, id) => collections[schema]?.find((row) => row.id === id),
getCollection: (schema) => collections[schema] || [],
getObjectByField: (schema) => collections[schema] || [],
createObject: (schema, value) => {
diff --git a/tests/services/client.test.ts b/tests/services/client.test.ts
index 7b1381530b..93a3ab1b81 100644
--- a/tests/services/client.test.ts
+++ b/tests/services/client.test.ts
@@ -3,24 +3,87 @@ import ElectrumClient from '../../src/services/electrum/client';
import { predefinedTestnetNodes } from '../../src/services/electrum/predefinedNodes';
import * as bitcoinJS from 'bitcoinjs-lib';
+const mockClients: any[] = [];
+const mockTxid = '24913105c497b4bb4ccf81b03857c8306aba0e58ccde792d981f6c18efdb24b8';
+
+// Exercise the real ElectrumClient facade against deterministic protocol replies.
+// Keep actual public-peer identities so production failover eligibility is tested,
+// while the protocol fixture avoids depending on public-server reachability.
+jest.mock('electrum-client', () => ({
+ __esModule: true,
+ default: jest.fn().mockImplementation((_net, _tls, _port, host) => {
+ const client = {
+ host,
+ initElectrum: jest.fn(async () => {
+ if (host === 'blackie.c3-soft.com') {
+ throw new Error('connect ECONNREFUSED 127.0.0.1:50002');
+ }
+ return ['fixture-server', '1.4'];
+ }),
+ close: jest.fn(),
+ onError: null,
+ server_ping: jest.fn(async () => undefined),
+ server_features: jest.fn(async () => ({
+ server_version: 'fixture-server',
+ protocol_min: '1.4',
+ protocol_max: '1.4.3',
+ })),
+ blockchainScripthash_listunspentBatch: jest.fn(async (hashes) =>
+ hashes.map((param, index) => ({
+ param,
+ result: index === 0 ? [{ tx_hash: mockTxid, tx_pos: 1, value: 12345, height: 100 }] : [],
+ }))
+ ),
+ blockchainScripthash_getHistoryBatch: jest.fn(async (hashes) =>
+ hashes.map((param, index) => ({
+ param,
+ result: index === 0 ? [{ tx_hash: mockTxid, height: 100 }] : [],
+ }))
+ ),
+ blockchainEstimatefee: jest.fn(async () => 0.00002),
+ blockchainTransaction_getBatch: jest.fn(async (txids) =>
+ txids.map((param) => ({
+ param,
+ result: {
+ txid: param,
+ hex: 'fixture-hex',
+ vout: [{ scriptPubKey: { address: 'tb1qfixture' } }],
+ },
+ }))
+ ),
+ };
+ mockClients.push(client);
+ return client;
+ }),
+}));
+
jest.mock('src/store/store', () => ({
store: {
getState: () => ({
- settings: {
- bitcoinNetwork: 'testnet',
- },
+ settings: { bitcoinNetworkType: 'TESTNET' },
}),
},
}));
-beforeAll(async () => {
- try {
- ElectrumClient.setActivePeer(predefinedTestnetNodes);
- await ElectrumClient.connect();
- } catch (err) {
- console.log('failed to connect to Electrum:', err);
- process.exit(1);
- }
+const onlineNode = {
+ ...predefinedTestnetNodes[1],
+ isConnected: true,
+};
+const offlineNode = {
+ ...predefinedTestnetNodes[0],
+ isConnected: true,
+};
+const addresses = [
+ 'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5',
+ 'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx',
+];
+
+beforeEach(async () => {
+ mockClients.length = 0;
+ ElectrumClient.setActivePeer([onlineNode], onlineNode);
+ ElectrumClient.resetCurrentPeerIndex();
+ const connection = await ElectrumClient.connect();
+ assert.ok(connection.connected);
});
afterAll(() => {
@@ -30,23 +93,33 @@ afterAll(() => {
describe('ElectrumClient', () => {
describe('Connection Tests', () => {
it('should test connection successfully', async () => {
- const result = await ElectrumClient.testConnection(predefinedTestnetNodes[0]);
+ const result = await ElectrumClient.testConnection(onlineNode);
assert.ok(result.connected);
});
it('should fail connection when node is unreachable', async () => {
- const unreachableNode = { ...predefinedTestnetNodes[0], host: 'invalid.host' };
- const result = await ElectrumClient.testConnection(unreachableNode);
+ const result = await ElectrumClient.testConnection(offlineNode);
assert.ok(!result.connected);
assert.ok(result.error);
+ assert.strictEqual(result.errorType, 'network');
});
it('should reconnect to the next peer when connection fails', async () => {
- ElectrumClient.setActivePeer(predefinedTestnetNodes);
+ ElectrumClient.setActivePeer([offlineNode, onlineNode], offlineNode);
+ ElectrumClient.resetCurrentPeerIndex();
+ const result = await ElectrumClient.connect();
+ assert.ok(result.connected);
+ assert.strictEqual(result.connectedTo, onlineNode.host);
+ assert.strictEqual(ElectrumClient.getActivePeer()?.host, onlineNode.host);
+
+ assert.ok(mockClients.some((client) => client.host === offlineNode.host));
+ });
+
+ it('should reconnect after explicit disconnection', async () => {
ElectrumClient.forceDisconnect();
const result = await ElectrumClient.reconnect();
assert.ok(result.connected);
- assert.ok(result.connectedTo);
+ assert.strictEqual(result.connectedTo, onlineNode.host);
});
});
@@ -60,51 +133,50 @@ describe('ElectrumClient', () => {
describe('Feature Tests', () => {
it('should retrieve server features', async () => {
const features = await ElectrumClient.serverFeatures();
- assert.ok(features.server_version);
- assert.ok(features.protocol_min);
- assert.ok(features.protocol_max);
+ assert.strictEqual(features.server_version, 'fixture-server');
+ assert.strictEqual(features.protocol_min, '1.4');
+ assert.strictEqual(features.protocol_max, '1.4.3');
});
});
describe('UTXO and History Tests', () => {
it('should sync UTXOs by address', async () => {
- const addresses = [
- 'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5',
- 'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx',
- ];
const utxos = await ElectrumClient.syncUTXOByAddress(addresses, bitcoinJS.networks.testnet);
- assert.ok(Object.keys(utxos).length > 0);
+ assert.deepStrictEqual(utxos[addresses[0]], [
+ { txId: mockTxid, vout: 1, value: 12345, height: 100, address: addresses[0] },
+ ]);
+ assert.deepStrictEqual(utxos[addresses[1]], []);
});
it('should sync history by address', async () => {
- const addresses = [
- 'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5',
- 'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx',
- ];
const history = await ElectrumClient.syncHistoryByAddress(
addresses,
bitcoinJS.networks.testnet
);
- assert.ok(Object.keys(history.historyByAddress).length > 0);
- assert.ok(history.txids.length > 0);
+ assert.deepStrictEqual(history.historyByAddress[addresses[0]], [
+ { tx_hash: mockTxid, height: 100 },
+ ]);
+ assert.deepStrictEqual(history.historyByAddress[addresses[1]], []);
+ assert.deepStrictEqual(history.txids, [mockTxid]);
+ assert.strictEqual(history.txidToAddress[mockTxid], addresses[0]);
});
});
describe('Transaction Tests', () => {
it('should estimate fee', async () => {
const fee = await ElectrumClient.estimateFee(1);
- assert.ok(fee > 0);
+ assert.strictEqual(fee, 2);
});
it('should fetch transactions by ID', async () => {
- const txids = [
- '24913105c497b4bb4ccf81b03857c8306aba0e58ccde792d981f6c18efdb24b8',
- '9a15008af30580039bc7a07d36c3544902a2e1618ad31f4dda94fe0044a8dcce',
- ];
+ const txids = [mockTxid, '9a15008af30580039bc7a07d36c3544902a2e1618ad31f4dda94fe0044a8dcce'];
const transactions = await ElectrumClient.getTransactionsById(txids);
- assert.ok(Object.keys(transactions).length === txids.length);
- assert.deepStrictEqual(transactions[txids[0]].txid, txids[0]);
- assert.deepStrictEqual(transactions[txids[1]].txid, txids[1]);
+ assert.deepStrictEqual(Object.keys(transactions), txids);
+ for (const txid of txids) {
+ assert.strictEqual(transactions[txid].txid, txid);
+ assert.strictEqual(transactions[txid].hex, undefined);
+ assert.deepStrictEqual(transactions[txid].vout[0].scriptPubKey.addresses, ['tb1qfixture']);
+ }
});
});
});
diff --git a/tests/services/electrumConnectionGeneration.test.ts b/tests/services/electrumConnectionGeneration.test.ts
new file mode 100644
index 0000000000..ba7ce5c351
--- /dev/null
+++ b/tests/services/electrumConnectionGeneration.test.ts
@@ -0,0 +1,219 @@
+import * as bitcoinJS from 'bitcoinjs-lib';
+import ElectrumClient, {
+ ELECTRUM_CONNECTION_CHANGED_ERR,
+} from '../../src/services/electrum/client';
+import {
+ predefinedMainnetNodes,
+ predefinedTestnetNodes,
+} from '../../src/services/electrum/predefinedNodes';
+import { NetworkType } from '../../src/services/wallets/enums';
+import dbManager from '../../src/storage/realm/dbManager';
+import { RealmSchema } from '../../src/storage/realm/enum';
+import { store } from '../../src/store/store';
+
+const mockClients: any[] = [];
+const mockInitReplies: Array<() => Promise> = [];
+let mockRealmAppId = 'account-a';
+const mockState = {
+ storage: { appId: 'account-a' },
+ settings: {
+ bitcoinNetworkType: NetworkType.TESTNET,
+ bitcoinNetwork: bitcoinJS.networks.testnet,
+ },
+};
+
+jest.mock('electrum-client', () => ({
+ __esModule: true,
+ default: jest.fn().mockImplementation(() => {
+ const client = {
+ initElectrum: jest.fn(
+ () => mockInitReplies.shift()?.() || Promise.resolve(['server', '1.4'])
+ ),
+ close: jest.fn(),
+ onError: null,
+ blockchainScripthash_listunspentBatch: jest.fn(),
+ blockchainScripthash_getHistoryBatch: jest.fn(),
+ blockchainTransaction_getBatch: jest.fn(),
+ };
+ mockClients.push(client);
+ return client;
+ }),
+}));
+jest.mock('src/store/store', () => ({
+ store: { getState: jest.fn(() => mockState), dispatch: jest.fn() },
+}));
+jest.mock('src/storage/realm/dbManager', () => ({
+ __esModule: true,
+ default: {
+ getObjectByIndex: jest.fn(() => ({ id: mockRealmAppId })),
+ updateObjectById: jest.fn(() => true),
+ },
+}));
+jest.mock('src/services/rest/RestClient', () => ({
+ __esModule: true,
+ default: { getTorStatus: jest.fn() },
+ TorStatus: { CONNECTED: 'connected' },
+}));
+jest.mock('src/services/electrum/torrific', () => ({ __esModule: true, default: {} }));
+
+const deferred = () => {
+ let resolve: (value: any) => void;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+};
+
+const testnetNode = () => ({ ...predefinedTestnetNodes[0], isConnected: false });
+const mainnetNode = () => ({ ...predefinedMainnetNodes[0], isConnected: false });
+
+describe('Electrum connection generation', () => {
+ beforeEach(() => {
+ mockRealmAppId = 'account-a';
+ mockState.storage.appId = 'account-a';
+ mockState.settings.bitcoinNetworkType = NetworkType.TESTNET;
+ mockState.settings.bitcoinNetwork = bitcoinJS.networks.testnet;
+ mockClients.length = 0;
+ mockInitReplies.length = 0;
+ jest.clearAllMocks();
+ });
+
+ afterEach(() => jest.useRealTimers());
+
+ it('ignores a late handshake and error callback from a replaced account connection', async () => {
+ const firstHandshake = deferred();
+ mockInitReplies.push(
+ () => firstHandshake.promise,
+ () => Promise.resolve(['server', '1.4'])
+ );
+ ElectrumClient.setActivePeer([testnetNode()], testnetNode());
+ const firstConnect = ElectrumClient.connect();
+ const firstClient = mockClients[0];
+
+ mockState.storage.appId = 'account-b';
+ mockRealmAppId = 'account-b';
+ ElectrumClient.setActivePeer([testnetNode()], testnetNode());
+ const currentResult = await ElectrumClient.connect();
+ const currentGeneration = ElectrumClient.getConnectionGeneration();
+
+ firstHandshake.resolve(['server', '1.4']);
+ await expect(firstConnect).resolves.toMatchObject({
+ connected: false,
+ error: ELECTRUM_CONNECTION_CHANGED_ERR,
+ });
+ firstClient.onError(new Error('old socket closed'));
+
+ expect(currentResult.connected).toBe(true);
+ expect(ElectrumClient.getConnectionGeneration()).toBe(currentGeneration);
+ expect(mockClients).toHaveLength(2);
+ expect(store.dispatch as jest.Mock).not.toHaveBeenCalled();
+ });
+
+ it('stops remaining UTXO batches if the selected network changes mid-request', async () => {
+ const selected = testnetNode();
+ ElectrumClient.setActivePeer([selected], selected);
+ await ElectrumClient.connect();
+ const pendingBatch = deferred();
+ mockClients[0].blockchainScripthash_listunspentBatch.mockReturnValue(pendingBatch.promise);
+ const address = 'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5';
+ const pendingSync = ElectrumClient.syncUTXOByAddress(
+ [address, address],
+ bitcoinJS.networks.testnet,
+ 1
+ );
+
+ mockState.settings.bitcoinNetworkType = NetworkType.MAINNET;
+ mockState.settings.bitcoinNetwork = bitcoinJS.networks.bitcoin;
+ const next = mainnetNode();
+ ElectrumClient.setActivePeer([next], next);
+ pendingBatch.resolve([]);
+
+ await expect(pendingSync).rejects.toThrow(ELECTRUM_CONNECTION_CHANGED_ERR);
+ expect(mockClients[0].blockchainScripthash_listunspentBatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects a Bitcoin network that differs from the active peer before sending', async () => {
+ const selected = testnetNode();
+ ElectrumClient.setActivePeer([selected], selected);
+ await ElectrumClient.connect();
+
+ await expect(
+ ElectrumClient.syncUTXOByAddress(['unused'], bitcoinJS.networks.bitcoin)
+ ).rejects.toThrow(ELECTRUM_CONNECTION_CHANGED_ERR);
+ expect(mockClients[0].blockchainScripthash_listunspentBatch).not.toHaveBeenCalled();
+ });
+
+ it('does not fetch another transaction chunk through a replaced connection', async () => {
+ const selected = testnetNode();
+ ElectrumClient.setActivePeer([selected], selected);
+ await ElectrumClient.connect();
+ const pendingBatch = deferred();
+ mockClients[0].blockchainTransaction_getBatch.mockReturnValue(pendingBatch.promise);
+ const pendingFetch = ElectrumClient.getTransactionsById(['first', 'second'], true, 1);
+
+ mockState.storage.appId = 'account-b';
+ mockRealmAppId = 'account-b';
+ ElectrumClient.setActivePeer([testnetNode()], testnetNode());
+ pendingBatch.resolve([]);
+
+ await expect(pendingFetch).rejects.toThrow(ELECTRUM_CONNECTION_CHANGED_ERR);
+ expect(mockClients[0].blockchainTransaction_getBatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('persists live public rotation and publishes the active server', async () => {
+ jest.useFakeTimers();
+ const first = testnetNode();
+ const fallback = { ...predefinedTestnetNodes[1], isConnected: false };
+ mockInitReplies.push(
+ () => Promise.resolve(['server', '1.4']),
+ () => Promise.reject(new Error('first server unavailable')),
+ () => Promise.resolve(['server', '1.4'])
+ );
+ ElectrumClient.setActivePeer([first, fallback], first);
+ await ElectrumClient.connect();
+
+ const reconnect = mockClients[0].onError(new Error('socket closed'));
+ await jest.advanceTimersByTimeAsync(500);
+ await reconnect;
+
+ expect(ElectrumClient.getActivePeer()?.id).toBe(fallback.id);
+ expect(dbManager.updateObjectById).toHaveBeenCalledWith(
+ RealmSchema.NodeConnect,
+ first.id.toString(),
+ { isConnected: false }
+ );
+ expect(dbManager.updateObjectById).toHaveBeenCalledWith(
+ RealmSchema.NodeConnect,
+ fallback.id.toString(),
+ { isConnected: true }
+ );
+ expect(store.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: { successful: true, connectedTo: fallback.host },
+ })
+ );
+ });
+
+ it('stops reconnect when Realm switches accounts before Redux catches up', async () => {
+ jest.useFakeTimers();
+ const selected = testnetNode();
+ ElectrumClient.setActivePeer([selected], selected);
+ await ElectrumClient.connect();
+ const generation = ElectrumClient.getConnectionGeneration();
+ const reconnect = mockClients[0].onError(new Error('socket closed'));
+
+ mockRealmAppId = 'account-b';
+ expect(() => ElectrumClient.assertConnectionGeneration(generation)).toThrow(
+ ELECTRUM_CONNECTION_CHANGED_ERR
+ );
+ await jest.advanceTimersByTimeAsync(500);
+ await expect(reconnect).resolves.toMatchObject({
+ connected: false,
+ error: ELECTRUM_CONNECTION_CHANGED_ERR,
+ });
+
+ expect(mockClients).toHaveLength(1);
+ expect(dbManager.updateObjectById).not.toHaveBeenCalled();
+ expect(store.dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/services/electrumWalletFixture.ts b/tests/services/electrumWalletFixture.ts
new file mode 100644
index 0000000000..466523c6ed
--- /dev/null
+++ b/tests/services/electrumWalletFixture.ts
@@ -0,0 +1,79 @@
+import ElectrumClient from 'src/services/electrum/client';
+import WalletOperations from 'src/services/wallets/operations';
+
+const fundingTxid = '608710eb040d935dedb6c4d6321369382b2bd45533a7442a6fa98add3860d46b';
+const previousTxid = '89b193b61f7681ee588939932219f3d92e54a1873a9fb823647038f3879fba00';
+const externalAddress = 'tb1ql7w62elx9ucw4pj5lgw4l028hmuw80sndtntxt';
+
+// The wallet and vault suites exercise address scanning, transaction parsing, coin selection,
+// and PSBT signing. Give each generated wallet one funded testnet address without using a
+// public Electrum server or a mutable public wallet balance.
+export const installElectrumWalletFixture = () => {
+ let fundedAddress: string | null = null;
+ const syncWallets = WalletOperations.syncWalletsViaElectrumClient;
+
+ jest.spyOn(WalletOperations, 'syncWalletsViaElectrumClient').mockImplementation((...args) => {
+ fundedAddress = null;
+ return syncWallets(...args);
+ });
+ jest.spyOn(WalletOperations, 'fetchFeeRatesByPriority').mockImplementation(async () =>
+ WalletOperations.mockFeeRates()
+ );
+
+ jest.spyOn(ElectrumClient, 'setActivePeer').mockImplementation(() => undefined);
+ jest.spyOn(ElectrumClient, 'connect').mockResolvedValue({
+ connected: true,
+ connectedTo: 'fixture.electrum.test',
+ });
+ jest.spyOn(ElectrumClient, 'forceDisconnect').mockImplementation(() => undefined);
+ jest.spyOn(ElectrumClient, 'getBlockchainHeaders').mockResolvedValue({ height: 85172, hex: '00' });
+ jest.spyOn(ElectrumClient, 'syncUTXOByAddress').mockImplementation(async (addresses) => {
+ if (!fundedAddress) fundedAddress = addresses[0];
+ return Object.fromEntries(
+ addresses.map((address) => [
+ address,
+ address === fundedAddress
+ ? [{ txId: fundingTxid, vout: 1, value: 6000, height: 85000, address }]
+ : [],
+ ])
+ );
+ });
+ jest.spyOn(ElectrumClient, 'syncHistoryByAddress').mockImplementation(async (addresses) => {
+ const hasFunding = addresses.includes(fundedAddress);
+ return {
+ historyByAddress: Object.fromEntries(
+ addresses.map((address) => [
+ address,
+ hasFunding && address === fundedAddress ? [{ tx_hash: fundingTxid, height: 85000 }] : [],
+ ])
+ ),
+ txids: hasFunding ? [fundingTxid] : [],
+ txidToAddress: hasFunding ? { [fundingTxid]: fundedAddress } : {},
+ };
+ });
+ jest.spyOn(ElectrumClient, 'getTransactionsById').mockImplementation(async (txids) => {
+ const transactions: Record = {};
+ for (const txid of txids) {
+ if (txid === fundingTxid) {
+ transactions[txid] = {
+ txid,
+ vin: [{ txid: previousTxid, vout: 0 }],
+ vout: [
+ { value: 0.00001, scriptPubKey: { addresses: [externalAddress] } },
+ { value: 0.00006, scriptPubKey: { addresses: [fundedAddress] } },
+ ],
+ confirmations: 12,
+ time: 1700000000,
+ blocktime: 1700000000,
+ };
+ } else if (txid === previousTxid) {
+ transactions[txid] = {
+ txid,
+ vin: [],
+ vout: [{ value: 0.0001, scriptPubKey: { addresses: [externalAddress] } }],
+ };
+ }
+ }
+ return transactions;
+ });
+};
diff --git a/tests/services/encryption.test.ts b/tests/services/encryption.test.ts
index 24a89e6a57..2c395c4ae2 100644
--- a/tests/services/encryption.test.ts
+++ b/tests/services/encryption.test.ts
@@ -82,7 +82,13 @@ describe('Testing cryptographic primitives', () => {
test('Decryption::Incorrect key', () => {
const incorrectKey = 'a'.repeat(64);
- const decrypted = decrypt(incorrectKey, encrypted);
+ let decrypted: string;
+ try {
+ decrypted = decrypt(incorrectKey, encrypt(key, message));
+ } catch (error) {
+ expect(error).toEqual(new Error('Malformed UTF-8 data'));
+ return;
+ }
expect(decrypted).not.toBe(message);
});
});
diff --git a/tests/services/faucetRequest.test.ts b/tests/services/faucetRequest.test.ts
new file mode 100644
index 0000000000..88051e36d4
--- /dev/null
+++ b/tests/services/faucetRequest.test.ts
@@ -0,0 +1,60 @@
+import Relay from '../../src/services/backend/Relay';
+import RestClient from '../../src/services/rest/RestClient';
+import { NetworkType } from '../../src/services/wallets/enums';
+
+jest.mock('src/services/rest/RestClient', () => ({
+ __esModule: true,
+ default: { post: jest.fn() },
+}));
+jest.mock('src/utils/service-utilities/config', () => ({
+ __esModule: true,
+ default: { RELAY: 'https://relay.example/' },
+}));
+jest.mock('src/services/sentry', () => ({ captureError: jest.fn() }));
+
+const post = RestClient.post as jest.Mock;
+const txid = 'a'.repeat(64);
+
+describe('Testnet faucet request', () => {
+ beforeEach(() => post.mockReset());
+
+ it('refuses a non-Testnet wallet before contacting the relay', async () => {
+ await expect(Relay.getTestcoins('address', NetworkType.MAINNET, 'app')).rejects.toThrow(
+ 'Invalid network'
+ );
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('sends a bounded, single request and returns a valid funded txid', async () => {
+ post.mockResolvedValue({ data: { txid, funded: true } });
+
+ await expect(Relay.getTestcoins('address', NetworkType.TESTNET, 'app')).resolves.toEqual({
+ txid,
+ funded: true,
+ });
+ expect(post).toHaveBeenCalledTimes(1);
+ expect(post).toHaveBeenCalledWith(
+ 'https://relay.example/testnetFaucet',
+ { recipientAddress: 'address', appId: 'app' },
+ undefined,
+ { timeout: 20000 }
+ );
+ });
+
+ it('marks a timed-out response as uncertain without retrying', async () => {
+ post.mockRejectedValue({ code: 'ECONNABORTED' });
+
+ await expect(Relay.getTestcoins('address', NetworkType.TESTNET, 'app')).rejects.toThrow(
+ 'FAUCET_OUTCOME_UNKNOWN'
+ );
+ expect(post).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the daily quota separate from an uncertain outcome', async () => {
+ post.mockRejectedValue({ response: { status: 429 } });
+
+ await expect(Relay.getTestcoins('address', NetworkType.TESTNET, 'app')).rejects.toThrow(
+ 'FAUCET_DAILY_LIMIT_REACHED'
+ );
+ });
+});
diff --git a/tests/services/faucetVisibility.test.ts b/tests/services/faucetVisibility.test.ts
new file mode 100644
index 0000000000..9b2c4cfc47
--- /dev/null
+++ b/tests/services/faucetVisibility.test.ts
@@ -0,0 +1,34 @@
+import { isFaucetTxVisible } from '../../src/store/sagas/faucetVisibility';
+
+const txid = 'a'.repeat(64);
+
+describe('faucet transaction visibility', () => {
+ it('requires the funded UTXO in persisted specs', () => {
+ const wallet = {
+ specs: {
+ balances: { confirmed: 0, unconfirmed: 1000 },
+ confirmedUTXOs: [],
+ unconfirmedUTXOs: [{ txId: txid }],
+ },
+ };
+ expect(isFaucetTxVisible(wallet, txid)).toBe(true);
+ expect(isFaucetTxVisible(wallet, 'b'.repeat(64))).toBe(false);
+ });
+
+ it('does not report receipt from a txid alone or before balance persistence', () => {
+ expect(isFaucetTxVisible({}, txid)).toBe(false);
+ expect(isFaucetTxVisible({ specs: { unconfirmedUTXOs: [{ txId: txid }] } }, txid)).toBe(false);
+ });
+
+ it('waits until the persisted balance shown on Home is positive', () => {
+ const wallet = {
+ specs: {
+ balances: { confirmed: 0, unconfirmed: 0 },
+ unconfirmedUTXOs: [{ txId: txid }],
+ },
+ };
+ expect(isFaucetTxVisible(wallet, txid)).toBe(false);
+ wallet.specs.balances.unconfirmed = 1000;
+ expect(isFaucetTxVisible(wallet, txid)).toBe(true);
+ });
+});
diff --git a/tests/services/manualNodeFailover.test.ts b/tests/services/manualNodeFailover.test.ts
new file mode 100644
index 0000000000..d6dabc3cbd
--- /dev/null
+++ b/tests/services/manualNodeFailover.test.ts
@@ -0,0 +1,51 @@
+import Node from '../../src/services/electrum/node';
+import ElectrumClient from '../../src/services/electrum/client';
+import {
+ predefinedMainnetNodes,
+ predefinedTestnetNodes,
+} from '../../src/services/electrum/predefinedNodes';
+
+jest.mock('src/services/electrum/client', () => ({
+ __esModule: true,
+ default: {
+ setActivePeer: jest.fn(),
+ connect: jest.fn(),
+ setFailoverPeers: jest.fn(),
+ },
+}));
+jest.mock('src/storage/realm/dbManager', () => ({ __esModule: true, default: {} }));
+jest.mock('src/store/store', () => ({ store: { getState: jest.fn() } }));
+
+describe('manual Electrum selection', () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ jest.clearAllMocks();
+ });
+
+ it('connects the tapped node first, then equips only same-network saved peers', async () => {
+ const selected = predefinedTestnetNodes[0];
+ const saved = [...predefinedTestnetNodes, predefinedMainnetNodes[0]];
+ jest.spyOn(Node, 'getAllNodes').mockReturnValue(saved);
+ (ElectrumClient.connect as jest.Mock).mockResolvedValue({
+ connected: true,
+ connectedTo: selected.host,
+ generation: 2,
+ });
+
+ await Node.connectToSelectedNode(selected);
+
+ expect(ElectrumClient.setActivePeer).toHaveBeenCalledWith([], selected);
+ expect(ElectrumClient.setFailoverPeers).toHaveBeenCalledWith(predefinedTestnetNodes, 2);
+ });
+
+ it('does not equip fallback peers when the tapped node never connects', async () => {
+ (ElectrumClient.connect as jest.Mock).mockResolvedValue({
+ connected: false,
+ error: 'unreachable',
+ });
+
+ await Node.connectToSelectedNode(predefinedTestnetNodes[0]);
+
+ expect(ElectrumClient.setFailoverPeers).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/services/networkConnectRace.test.ts b/tests/services/networkConnectRace.test.ts
new file mode 100644
index 0000000000..d21c012606
--- /dev/null
+++ b/tests/services/networkConnectRace.test.ts
@@ -0,0 +1,154 @@
+import { runSaga } from 'redux-saga';
+import ElectrumClient from '../../src/services/electrum/client';
+import { predefinedTestnetNodes } from '../../src/services/electrum/predefinedNodes';
+import { NetworkType } from '../../src/services/wallets/enums';
+import dbManager from '../../src/storage/realm/dbManager';
+import { RealmSchema } from '../../src/storage/realm/enum';
+import { connectToNodeWorker } from '../../src/store/sagas/network';
+
+let mockGeneration = 0;
+let mockRealmAppId = 'account-a';
+const mockNodes = predefinedTestnetNodes;
+const mockState = {
+ settings: { bitcoinNetworkType: NetworkType.TESTNET },
+ storage: { appId: 'account-a' },
+ network: {
+ initialNodesSaved: true,
+ testnetFallbackNodeAddedByAppId: { 'account-a': true },
+ },
+};
+
+jest.mock('src/store/store', () => ({ store: { getState: jest.fn(() => mockState) } }));
+jest.mock('src/storage/realm/dbManager', () => ({
+ __esModule: true,
+ default: {
+ getObjectByIndex: jest.fn(() => ({ id: mockRealmAppId })),
+ getCollection: jest.fn(() => mockNodes),
+ createObject: jest.fn(() => true),
+ updateObjectById: jest.fn(() => true),
+ },
+}));
+jest.mock('src/services/electrum/client', () => ({
+ __esModule: true,
+ default: {
+ setActivePeer: jest.fn(() => {
+ mockGeneration += 1;
+ }),
+ connect: jest.fn(),
+ getConnectionGeneration: jest.fn(() => mockGeneration),
+ getActivePeer: jest.fn(() => mockNodes[0]),
+ },
+}));
+jest.mock('src/services/sentry', () => ({ captureError: jest.fn() }));
+
+const deferred = () => {
+ let resolve: (value: any) => void;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+};
+
+describe('overlapping Electrum connection workers', () => {
+ beforeEach(() => {
+ mockGeneration = 0;
+ mockRealmAppId = 'account-a';
+ mockState.storage.appId = 'account-a';
+ jest.clearAllMocks();
+ (ElectrumClient.connect as jest.Mock).mockReset();
+ (dbManager.getCollection as jest.Mock).mockReturnValue(mockNodes);
+ });
+
+ it('does not publish a late result from the older worker', async () => {
+ const first = deferred();
+ const second = deferred();
+ (ElectrumClient.connect as jest.Mock)
+ .mockImplementationOnce(() => {
+ mockGeneration += 1;
+ return first.promise;
+ })
+ .mockImplementationOnce(() => {
+ mockGeneration += 1;
+ return second.promise;
+ });
+ const actions: any[] = [];
+ const environment = {
+ dispatch: (action) => actions.push(action),
+ getState: () => mockState,
+ };
+
+ const firstTask = runSaga(environment, connectToNodeWorker);
+ const secondTask = runSaga(environment, connectToNodeWorker);
+ expect(ElectrumClient.connect).toHaveBeenCalledTimes(2);
+
+ second.resolve({ connected: true, connectedTo: 'winner', generation: mockGeneration });
+ await secondTask.toPromise();
+ first.resolve({ connected: false, error: 'old failure', generation: mockGeneration - 2 });
+ await firstTask.toPromise();
+
+ const connectionResults = actions.filter(
+ (action) => action.type === 'login/electrumClientConnectionExecuted'
+ );
+ expect(connectionResults).toEqual([
+ expect.objectContaining({ payload: { successful: true, connectedTo: 'winner' } }),
+ ]);
+ expect(dbManager.getCollection).toHaveBeenCalled();
+ });
+
+ it('adds the Testnet fallback for a second account despite the first account marker', async () => {
+ mockState.storage.appId = 'account-b';
+ mockRealmAppId = 'account-b';
+ (dbManager.getCollection as jest.Mock).mockReturnValue([mockNodes[0]]);
+ (ElectrumClient.connect as jest.Mock).mockImplementation(() => {
+ mockGeneration += 1;
+ return Promise.resolve({
+ connected: true,
+ connectedTo: mockNodes[0].host,
+ generation: mockGeneration,
+ });
+ });
+ const actions: any[] = [];
+
+ await runSaga(
+ { dispatch: (action) => actions.push(action), getState: () => mockState },
+ connectToNodeWorker
+ ).toPromise();
+
+ expect(dbManager.createObject).toHaveBeenCalledWith(RealmSchema.NodeConnect, mockNodes[1]);
+ expect(actions).toContainEqual(
+ expect.objectContaining({
+ type: 'network/setTestnetFallbackNodeAdded',
+ payload: 'account-b',
+ })
+ );
+ });
+
+ it('does not write node flags into the newly opened Realm while Redux still names the old app', async () => {
+ const pendingConnection = deferred();
+ (ElectrumClient.connect as jest.Mock).mockImplementation(() => {
+ mockGeneration += 1;
+ return pendingConnection.promise;
+ });
+ (ElectrumClient.getActivePeer as jest.Mock).mockReturnValue(mockNodes[1]);
+ const actions: any[] = [];
+ const task = runSaga(
+ { dispatch: (action) => actions.push(action), getState: () => mockState },
+ connectToNodeWorker
+ );
+ expect(ElectrumClient.connect).toHaveBeenCalledTimes(1);
+
+ mockRealmAppId = 'account-b';
+ pendingConnection.resolve({
+ connected: true,
+ connectedTo: mockNodes[1].host,
+ generation: mockGeneration,
+ });
+ await task.toPromise();
+
+ expect(mockState.storage.appId).toBe('account-a');
+ expect(dbManager.updateObjectById).not.toHaveBeenCalled();
+ expect(
+ actions.filter((action) => action.type === 'login/electrumClientConnectionExecuted')
+ ).toEqual([]);
+ });
+});
diff --git a/tests/services/networkFailover.test.ts b/tests/services/networkFailover.test.ts
new file mode 100644
index 0000000000..a65eefa84a
--- /dev/null
+++ b/tests/services/networkFailover.test.ts
@@ -0,0 +1,42 @@
+import { getFailoverPeers } from '../../src/services/electrum/peerSelection';
+import {
+ predefinedMainnetNodes,
+ predefinedTestnetNodes,
+} from '../../src/services/electrum/predefinedNodes';
+
+describe('Electrum failover peer selection', () => {
+ it('retries only the selected private node', () => {
+ const privateNode = {
+ ...predefinedTestnetNodes[0],
+ id: 1001,
+ host: 'private.example',
+ };
+
+ expect(getFailoverPeers([predefinedTestnetNodes[0], privateNode], privateNode)).toEqual([
+ privateNode,
+ ]);
+ });
+
+ it('uses saved public peers on the same network and never a private node', () => {
+ const privateNode = {
+ ...predefinedTestnetNodes[0],
+ id: 1001,
+ host: 'private.example',
+ };
+ const peers = getFailoverPeers(
+ [
+ predefinedMainnetNodes[0],
+ predefinedTestnetNodes[1],
+ privateNode,
+ predefinedTestnetNodes[0],
+ ],
+ predefinedTestnetNodes[0]
+ );
+
+ expect(peers).toEqual(predefinedTestnetNodes);
+ });
+
+ it('does not reconnect after an explicit disconnect', () => {
+ expect(getFailoverPeers(predefinedTestnetNodes, null)).toEqual([]);
+ });
+});
diff --git a/tests/services/passphraseDecayPolicy.test.ts b/tests/services/passphraseDecayPolicy.test.ts
new file mode 100644
index 0000000000..7b33ab80f5
--- /dev/null
+++ b/tests/services/passphraseDecayPolicy.test.ts
@@ -0,0 +1,122 @@
+import * as bip39 from 'bip39';
+import {
+ generateSeedWordsKey,
+ generateMiniscriptScheme,
+ generateVault,
+} from 'src/services/wallets/factories/VaultFactory';
+import { MiniscriptTypes, MultisigScriptType, NetworkType, VaultType } from 'src/services/wallets/enums';
+import {
+ ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET,
+ generateEnhancedVaultElements,
+} from 'src/services/wallets/operations/miniscript/default/EnhancedVault';
+import WalletUtilities from 'src/services/wallets/operations/utils';
+import WalletOperations from 'src/services/wallets/operations';
+import { generateOutputDescriptors } from 'src/utils/service-utilities/utils';
+
+jest.mock('src/store/store', () => ({
+ store: { getState: () => ({ settings: { bitcoinNetworkType: 'MAINNET' } }) },
+}));
+const mnemonic = bip39.entropyToMnemonic('00000000000000000000000000000000');
+const networkType = NetworkType.MAINNET;
+const network = WalletUtilities.getNetworkByType(networkType);
+const derivationPath = WalletUtilities.getDerivationPath(true, networkType);
+
+const externalSigner = (passphrase: string) => {
+ const masterFingerprint = WalletUtilities.getMasterFingerprintFromMnemonic(mnemonic, passphrase);
+ return {
+ masterFingerprint,
+ xfp: masterFingerprint,
+ derivationPath,
+ xpub: WalletUtilities.generateExtendedKey(
+ mnemonic,
+ false,
+ network,
+ derivationPath,
+ passphrase
+ ),
+ };
+};
+
+describe('Disposable passphrase and absolute-lock policy fixture', () => {
+ it('derives distinct signer keys from the same public test words with and without a passphrase', () => {
+ const primary = externalSigner('TREZOR');
+ const inheritance = externalSigner('');
+ const inAppSeedWordsKey = generateSeedWordsKey(mnemonic, networkType, true);
+
+ expect(primary.masterFingerprint).not.toBe(inheritance.masterFingerprint);
+ expect(primary.xpub).not.toBe(inheritance.xpub);
+ expect(inAppSeedWordsKey.xpub).toBe(inheritance.xpub);
+ expect(inAppSeedWordsKey.xpub).not.toBe(primary.xpub);
+ });
+
+ it('compiles a one-key inheritance branch at one fixed six-month mainnet timestamp', () => {
+ const primary = externalSigner('TREZOR');
+ const inheritance = externalSigner('');
+ const fixedStart = 1800000000;
+ // Production's MONTHS_6 is a fixed 180-day interval; Testnet uses a shorter fixture interval.
+ expect(ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET.MONTHS_6).toBe(180 * 24 * 60 * 60);
+ const absoluteUnlock = fixedStart + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET.MONTHS_6;
+ const elements = generateEnhancedVaultElements(
+ [primary],
+ [{ signer: inheritance, timelock: absoluteUnlock }],
+ [],
+ { m: 1, n: 1 },
+ 0
+ );
+ const scheme = generateMiniscriptScheme(elements, [MiniscriptTypes.INHERITANCE]);
+
+ expect(scheme.miniscriptPolicy).toContain(`after(${absoluteUnlock})`);
+ expect(scheme.miniscriptPolicy).toContain('pk(IK1');
+ expect(scheme.miniscriptPolicy).toContain('pk(K1');
+ expect(scheme.miniscript).toBeTruthy();
+ expect(scheme.miniscriptElements.timelocks).toEqual([absoluteUnlock]);
+ expect(Object.values(scheme.keyInfoMap)).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining(`${primary.xpub}/<`),
+ expect.stringContaining(`${inheritance.xpub}/<`),
+ ])
+ );
+ expect(Object.values(scheme.keyInfoMap).every((key) => key.endsWith('/*'))).toBe(true);
+ });
+
+ it('derives two receive addresses from a Vault descriptor with the same absolute unlock', async () => {
+ const primary = externalSigner('TREZOR');
+ const inheritance = externalSigner('');
+ const absoluteUnlock = 1800000000 + ENHANCED_VAULT_TIMELOCKS_TIMESTAMP_MAINNET.MONTHS_6;
+ const miniscriptScheme = generateMiniscriptScheme(
+ generateEnhancedVaultElements(
+ [primary],
+ [{ signer: inheritance, timelock: absoluteUnlock }],
+ [],
+ { m: 1, n: 1 },
+ 0
+ ),
+ [MiniscriptTypes.INHERITANCE]
+ );
+ const vault = await generateVault({
+ type: VaultType.MINISCRIPT,
+ vaultName: 'Disposable policy fixture',
+ vaultDescription: '',
+ scheme: {
+ m: 1,
+ n: 1,
+ multisigScriptType: MultisigScriptType.MINISCRIPT_MULTISIG,
+ miniscriptScheme,
+ },
+ signers: [primary, inheritance],
+ networkType,
+ });
+ const descriptor = generateOutputDescriptors(vault);
+ const first = WalletOperations.getExternalInternalAddressAtIdx(vault, 0);
+ const second = WalletOperations.getExternalInternalAddressAtIdx(vault, 1);
+
+ expect(descriptor).toContain(`after(${absoluteUnlock})`);
+ expect(descriptor).toContain(`[${primary.masterFingerprint}/48h/0h/0h/2h]`);
+ expect(descriptor).toContain(`[${inheritance.masterFingerprint}/48h/0h/0h/2h]`);
+ expect(descriptor).toContain(`${primary.xpub}/<`);
+ expect(descriptor).toContain(`${inheritance.xpub}/<`);
+ expect(descriptor).toContain('/*');
+ expect(descriptor).toContain('#');
+ expect(first).not.toBe(second);
+ });
+});
diff --git a/tests/services/restClient.requestConfig.test.ts b/tests/services/restClient.requestConfig.test.ts
new file mode 100644
index 0000000000..565221e15c
--- /dev/null
+++ b/tests/services/restClient.requestConfig.test.ts
@@ -0,0 +1,53 @@
+import axios from 'axios';
+import RestClient from '../../src/services/rest/RestClient';
+
+jest.mock('axios');
+jest.mock('react-native-device-info', () => ({
+ getVersion: () => 'test',
+ getBuildNumber: () => '1',
+}));
+jest.mock('src/utils/service-utilities/config', () => ({
+ __esModule: true,
+ default: { HEXA_ID: 'test-id' },
+}));
+
+describe('RestClient request options', () => {
+ beforeEach(() => {
+ (axios.get as jest.Mock).mockResolvedValue({ data: {} });
+ (axios.post as jest.Mock).mockResolvedValue({ data: {} });
+ });
+
+ it('passes GET deadline to Axios instead of sending it as an HTTP header', async () => {
+ await RestClient.get('https://example.test/status', { Authorization: 'test' }, { timeout: 20 });
+
+ expect(axios.get).toHaveBeenCalledWith(
+ 'https://example.test/status',
+ expect.objectContaining({
+ timeout: 20,
+ headers: expect.objectContaining({ Authorization: 'test' }),
+ })
+ );
+ expect((axios.get as jest.Mock).mock.calls[0][1].headers.timeout).toBeUndefined();
+ });
+
+ it('forwards POST cancellation without losing existing headers', async () => {
+ const controller = new AbortController();
+ await RestClient.post(
+ 'https://example.test/request',
+ {},
+ { Authorization: 'test' },
+ {
+ signal: controller.signal,
+ }
+ );
+
+ expect(axios.post).toHaveBeenCalledWith(
+ 'https://example.test/request',
+ {},
+ expect.objectContaining({
+ signal: controller.signal,
+ headers: expect.objectContaining({ Authorization: 'test', 'HEXA-ID': 'test-id' }),
+ })
+ );
+ });
+});
diff --git a/tests/services/testnetFallbackMigration.test.ts b/tests/services/testnetFallbackMigration.test.ts
new file mode 100644
index 0000000000..e82a9ac446
--- /dev/null
+++ b/tests/services/testnetFallbackMigration.test.ts
@@ -0,0 +1,15 @@
+import networkReducer, { setTestnetFallbackNodeAdded } from '../../src/store/reducers/network';
+
+describe('Testnet fallback migration', () => {
+ it('tracks each account separately so a second Realm receives its own fallback', () => {
+ const firstAccount = networkReducer(undefined, setTestnetFallbackNodeAdded('account-a'));
+ expect(firstAccount.testnetFallbackNodeAddedByAppId['account-a']).toBe(true);
+ expect(firstAccount.testnetFallbackNodeAddedByAppId['account-b']).toBeUndefined();
+
+ const secondAccount = networkReducer(firstAccount, setTestnetFallbackNodeAdded('account-b'));
+ expect(secondAccount.testnetFallbackNodeAddedByAppId).toEqual({
+ 'account-a': true,
+ 'account-b': true,
+ });
+ });
+});
diff --git a/tests/services/vault.test.ts b/tests/services/vault.test.ts
index ed6cf6f13b..2dd93f2329 100644
--- a/tests/services/vault.test.ts
+++ b/tests/services/vault.test.ts
@@ -43,6 +43,7 @@ import {
generateOutputDescriptors,
parseTextforVaultConfig,
} from 'src/utils/service-utilities/utils';
+import { installElectrumWalletFixture } from './electrumWalletFixture';
jest.mock('src/store/store', () => ({
store: {
@@ -56,6 +57,10 @@ jest.mock('src/store/store', () => ({
jest.mock('realm', () => ({}));
+beforeAll(() => {
+ installElectrumWalletFixture();
+});
+
const connectToElectrumClient = async () => {
try {
ElectrumClient.setActivePeer(predefinedTestnetNodes);
diff --git a/tests/services/wallet.test.ts b/tests/services/wallet.test.ts
index dc92142d4f..b366993e46 100644
--- a/tests/services/wallet.test.ts
+++ b/tests/services/wallet.test.ts
@@ -12,6 +12,7 @@ import {
TransactionPrerequisite,
} from 'src/services/wallets/interfaces';
import { Wallet } from 'src/services/wallets/interfaces/wallet';
+import { installElectrumWalletFixture } from './electrumWalletFixture';
jest.mock('src/store/store', () => ({
store: {
@@ -25,6 +26,10 @@ jest.mock('src/store/store', () => ({
jest.mock('realm', () => ({}));
+beforeAll(() => {
+ installElectrumWalletFixture();
+});
+
describe('Wallet Functionality Tests', () => {
let primaryMnemonic: string;
let wallet: Wallet;
diff --git a/tests/sync/walletRefresh.test.cjs b/tests/sync/walletRefresh.test.cjs
new file mode 100644
index 0000000000..af5b8e823b
--- /dev/null
+++ b/tests/sync/walletRefresh.test.cjs
@@ -0,0 +1,60 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { selectWalletsForSync } = require('../../src/store/sagas/walletSyncSelection.js');
+const { acquireWalletRefresh } = require('../../src/store/sagas/walletRefreshCoordinator.js');
+
+const wallet = (id, networkType, archived = false, visibility = 'DEFAULT') => ({
+ id, networkType, archived, entityKind: 'VAULT', presentationData: { visibility },
+ specs: { balances: { confirmed: 0, unconfirmed: 0 } },
+});
+
+test('automatic sync retains empty and hidden archived vaults on the selected network', () => {
+ const main = wallet('main', 'MAINNET');
+ const emptyArchive = wallet('empty-archive', 'TESTNET', true, 'HIDDEN');
+ const otherNetworkArchive = wallet('other-archive', 'MAINNET', true);
+ const activeTestnet = wallet('active', 'TESTNET');
+ const selected = selectWalletsForSync([main], [emptyArchive, otherNetworkArchive, activeTestnet], 'TESTNET');
+ assert.deepEqual(selected.active.map((item) => item.id), ['active']);
+ assert.deepEqual(selected.archived.map((item) => item.id), ['empty-archive']);
+
+ const resumed = selectWalletsForSync([], [emptyArchive, activeTestnet], 'TESTNET', {
+ archivedOnly: true,
+ });
+ assert.deepEqual(resumed.active, []);
+ assert.deepEqual(resumed.archived.map((item) => item.id), ['empty-archive']);
+});
+
+test('identical requests join and overlapping wallet refreshes wait for the first write', async () => {
+ const current = wallet('dedup', 'TESTNET');
+ const first = acquireWalletRefresh('profile-a', 'TESTNET', [current], { hardRefresh: false });
+ const duplicate = acquireWalletRefresh('profile-a', 'TESTNET', [current], { hardRefresh: false });
+ const harder = acquireWalletRefresh('profile-a', 'TESTNET', [current], { hardRefresh: true });
+ assert.equal(first.owner, true);
+ assert.equal(duplicate.owner, false);
+ assert.equal(duplicate.done, first.done);
+ assert.equal(harder.owner, true);
+
+ let harderReady = false;
+ harder.ready.then(() => { harderReady = true; });
+ await Promise.resolve();
+ assert.equal(harderReady, false);
+ first.complete(true);
+ assert.equal(await duplicate.done, true);
+ await harder.ready;
+ assert.equal(harderReady, true);
+ harder.complete(true);
+});
+
+test('refresh queues are isolated by profile and network', async () => {
+ const current = wallet('shared-xpub', 'TESTNET');
+ const first = acquireWalletRefresh('profile-a', 'TESTNET', [current]);
+ const otherProfile = acquireWalletRefresh('profile-b', 'TESTNET', [current]);
+ const otherNetwork = acquireWalletRefresh('profile-a', 'MAINNET', [current]);
+ await Promise.all([otherProfile.ready, otherNetwork.ready]);
+ assert.equal(otherProfile.owner, true);
+ assert.equal(otherNetwork.owner, true);
+ otherProfile.complete(true);
+ otherNetwork.complete(true);
+ first.complete(false);
+ assert.equal(await first.done, false);
+});