Implement background sync for xmr using flutter_daemon (#2094)

* Implement background sync for xmr using flutter_daemon

* - initialize app config in background thread
- initializeAppConfigs without loading the wallet.

* - properly do awaited calls in methodChannel
- prevent locking main thread during background sync

* add back background sync debug page
fix issues caused by xmr wallet being view only (and read only)

* changes from review
improve starting of bgsync task

* update stopBackgroundSync, await listener functions, ensure that listener always start (call _start in constructor)

* DO-NOT-MERGE: extre verbose monero logs

* stop background service when app is being opened

* improve monitoring of background sync

* update flutter_daemon to ensure network constraint
prevent throwing errors on isBackgroundSyncEnabled
check network before syncing

* Update lib/main.dart

* revert Update main.dart [skip ci]

* continously run network check

* disable charging requirement,
fix status reporting of background sync in UI

* Refactor background sync logic, and add UI notifications for battery optimization. Updated flutter_daemon version modified build.gradle for signing config to allow testing in both release and debug modes.

* verbose monero only when requested in code.
Do not start background sync when battery optimization is on

* fix background sync mode not properly reflecting state changes

* drop unnecessary dependency

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
This commit is contained in:
cyan
2025-03-21 19:22:00 +02:00
committed by GitHub
co-authored by Omar Hatem
parent d44621e6c7
commit 686580ff78
60 changed files with 853 additions and 352 deletions
+107
View File
@@ -0,0 +1,107 @@
import 'dart:async';
import 'dart:math';
import 'package:cake_wallet/core/key_service.dart';
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/view_model/wallet_list/wallet_list_item.dart';
import 'package:cake_wallet/view_model/wallet_list/wallet_list_view_model.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class BackgroundSync {
Future<void> sync() async {
printV("Background sync started");
await _syncMonero();
printV("Background sync completed");
}
Future<void> _syncMonero() async {
final walletLoadingService = getIt.get<WalletLoadingService>();
final walletListViewModel = getIt.get<WalletListViewModel>();
final settingsStore = getIt.get<SettingsStore>();
final List<WalletListItem> moneroWallets = walletListViewModel.wallets
.where((element) => !element.isHardware)
.where((element) => [WalletType.monero].contains(element.type))
.toList();
for (int i = 0; i < moneroWallets.length; i++) {
final wallet = await walletLoadingService.load(moneroWallets[i].type, moneroWallets[i].name);
int syncedTicks = 0;
final keyService = getIt.get<KeyService>();
int stuckTicks = 0;
inner:
while (true) {
await Future.delayed(const Duration(seconds: 1));
final syncStatus = wallet.syncStatus;
final progress = syncStatus.progress();
if (syncStatus is ConnectedSyncStatus || syncStatus is AttemptingSyncStatus || syncStatus is NotConnectedSyncStatus) {
stuckTicks++;
if (stuckTicks > 30) {
printV("${wallet.name} STUCK SYNCING");
break inner;
}
} else {
stuckTicks = 0;
}
if (syncStatus is NotConnectedSyncStatus) {
printV("${wallet.name} NOT CONNECTED");
final node = settingsStore.getCurrentNode(wallet.type);
await wallet.connectToNode(node: node);
await wallet.startBackgroundSync();
printV("STARTED SYNC");
continue inner;
}
if (progress > 0.999 || syncStatus is SyncedSyncStatus) {
syncedTicks++;
if (syncedTicks > 5) {
syncedTicks = 0;
printV("WALLET $i SYNCED");
try {
await wallet.stopBackgroundSync((await keyService.getWalletPassword(walletName: wallet.name)));
} catch (e) {
printV("error stopping sync: $e");
}
break inner;
}
} else {
syncedTicks = 0;
}
if (kDebugMode) {
if (syncStatus is SyncingSyncStatus) {
final blocksLeft = syncStatus.blocksLeft;
printV("$blocksLeft Blocks Left");
} else if (syncStatus is SyncedSyncStatus) {
printV("Synced");
} else if (syncStatus is SyncedTipSyncStatus) {
printV("Scanned Tip: ${syncStatus.tip}");
} else if (syncStatus is NotConnectedSyncStatus) {
printV("Still Not Connected");
} else if (syncStatus is AttemptingSyncStatus) {
printV("Attempting Sync");
} else if (syncStatus is StartingScanSyncStatus) {
printV("Starting Scan");
} else if (syncStatus is SyncronizingSyncStatus) {
printV("Syncronizing");
} else if (syncStatus is FailedSyncStatus) {
printV("Failed Sync");
} else if (syncStatus is ConnectingSyncStatus) {
printV("Connecting");
} else {
printV("Unknown Sync Status ${syncStatus.runtimeType}");
}
}
}
await wallet.stopBackgroundSync(await keyService.getWalletPassword(walletName: wallet.name));
await wallet.close(shouldCleanup: true);
}
}
}
+9 -5
View File
@@ -26,7 +26,6 @@ import 'package:cake_wallet/core/wallet_connect/web3wallet_service.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cake_wallet/core/yat_service.dart';
import 'package:cake_wallet/entities/background_tasks.dart';
import 'package:cake_wallet/entities/biometric_auth.dart';
import 'package:cake_wallet/entities/contact.dart';
import 'package:cake_wallet/entities/contact_record.dart';
@@ -34,6 +33,9 @@ import 'package:cake_wallet/entities/exchange_api_mode.dart';
import 'package:cake_wallet/entities/hardware_wallet/require_hardware_wallet_connection.dart';
import 'package:cake_wallet/entities/parse_address_from_domain.dart';
import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
import 'package:cake_wallet/src/screens/dev/monero_background_sync.dart';
import 'package:cake_wallet/src/screens/settings/background_sync_page.dart';
import 'package:cake_wallet/view_model/dev/monero_background_sync.dart';
import 'package:cake_wallet/view_model/link_view_model.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/src/screens/transaction_details/rbf_details_page.dart';
@@ -309,9 +311,6 @@ Future<void> setup({
getIt.registerSingletonAsync<SharedPreferences>(() => SharedPreferences.getInstance());
getIt.registerSingleton<SecureStorage>(secureStorage);
}
if (!_isSetupFinished) {
getIt.registerFactory(() => BackgroundTasks());
}
final isBitcoinBuyEnabled = (secrets.wyreSecretKey.isNotEmpty) &&
(secrets.wyreApiKey.isNotEmpty) &&
@@ -909,6 +908,8 @@ Future<void> setup({
getIt.registerFactory<SeedSettingsViewModel>(() => SeedSettingsViewModel(getIt.get<AppStore>(), getIt.get<SeedSettingsStore>()));
getIt.registerFactory(() => DevMoneroBackgroundSync(getIt.get<AppStore>().wallet!));
getIt.registerFactoryParam<WalletSeedPage, bool, void>((bool isWalletCreated, _) =>
WalletSeedPage(getIt.get<WalletSeedViewModel>(), isNewWalletCreated: isWalletCreated));
@@ -1068,6 +1069,8 @@ Future<void> setup({
getIt.registerFactory(
() => ExchangeTradeExternalSendPage(exchangeTradeViewModel: getIt.get<ExchangeTradeViewModel>()));
getIt.registerFactory(() => BackgroundSyncPage(getIt.get<DashboardViewModel>()));
getIt.registerFactory(() => ExchangeTemplatePage(getIt.get<ExchangeViewModel>()));
getIt.registerFactoryParam<WalletService, WalletType, void>((WalletType param1, __) {
@@ -1443,7 +1446,8 @@ Future<void> setup({
getIt.registerFactory(() => SignViewModel(getIt.get<AppStore>().wallet!));
getIt.registerFactory(() => SeedVerificationPage(getIt.get<WalletSeedViewModel>()));
getIt.registerFactory(() => SeedVerificationPage(getIt.get<WalletSeedViewModel>()));
getIt.registerFactory(() => DevMoneroBackgroundSyncPage(getIt.get<DevMoneroBackgroundSync>()));
_isSetupFinished = true;
}
-166
View File
@@ -1,166 +0,0 @@
import 'dart:io';
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/device_info.dart';
import 'package:cake_wallet/utils/feature_flag.dart';
import 'package:cake_wallet/view_model/settings/sync_mode.dart';
import 'package:cake_wallet/view_model/wallet_list/wallet_list_item.dart';
import 'package:cake_wallet/view_model/wallet_list/wallet_list_view_model.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workmanager/workmanager.dart';
import 'package:cake_wallet/main.dart';
import 'package:cake_wallet/di.dart';
const moneroSyncTaskKey = "com.fotolockr.cakewallet.monero_sync_task";
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
try {
switch (task) {
case moneroSyncTaskKey:
/// The work manager runs on a separate isolate from the main flutter isolate.
/// thus we initialize app configs first; hive, getIt, etc...
await initializeAppConfigs();
final walletLoadingService = getIt.get<WalletLoadingService>();
final typeRaw = getIt.get<SharedPreferences>().getInt(PreferencesKey.currentWalletType);
WalletBase? wallet;
if (inputData!['sync_all'] as bool) {
/// get all Monero wallets of the user and sync them
final List<WalletListItem> moneroWallets = getIt
.get<WalletListViewModel>()
.wallets
.where((element) => [WalletType.monero, WalletType.wownero].contains(element.type))
.toList();
for (int i = 0; i < moneroWallets.length; i++) {
wallet =
await walletLoadingService.load(moneroWallets[i].type, moneroWallets[i].name);
final node = getIt.get<SettingsStore>().getCurrentNode(moneroWallets[i].type);
await wallet.connectToNode(node: node);
await wallet.startSync();
}
} else {
/// if the user chose to sync only active wallet
/// if the current wallet is monero; sync it only
if (typeRaw == WalletType.monero.index || typeRaw == WalletType.wownero.index) {
final name =
getIt.get<SharedPreferences>().getString(PreferencesKey.currentWalletName);
wallet = await walletLoadingService.load(WalletType.values[typeRaw!], name!);
final node = getIt.get<SettingsStore>().getCurrentNode(WalletType.values[typeRaw]);
await wallet.connectToNode(node: node);
await wallet.startSync();
}
}
if (wallet?.syncStatus.progress() == null) {
return Future.error("No Monero/Wownero wallet found");
}
for (int i = 0;; i++) {
await Future<void>.delayed(const Duration(seconds: 1));
if (wallet?.syncStatus.progress() == 1.0) {
break;
}
if (i > 600) {
return Future.error("Synchronization Timed out");
}
}
break;
}
return Future.value(true);
} catch (error, stackTrace) {
printV(error);
printV(stackTrace);
return Future.error(error);
}
});
}
class BackgroundTasks {
void registerSyncTask({bool changeExisting = false}) async {
try {
bool hasMonero = getIt
.get<WalletListViewModel>()
.wallets
.any((element) => element.type == WalletType.monero);
/// if its not android nor ios, or the user has no monero wallets; exit
if (!DeviceInfo.instance.isMobile || !hasMonero) {
return;
}
final settingsStore = getIt.get<SettingsStore>();
final SyncMode syncMode = settingsStore.currentSyncMode;
final bool syncAll = settingsStore.currentSyncAll;
if (syncMode.type == SyncType.disabled || !FeatureFlag.isBackgroundSyncEnabled) {
cancelSyncTask();
return;
}
await Workmanager().initialize(
callbackDispatcher,
isInDebugMode: kDebugMode,
);
final inputData = <String, dynamic>{"sync_all": syncAll};
final constraints = Constraints(
networkType:
syncMode.type == SyncType.unobtrusive ? NetworkType.unmetered : NetworkType.connected,
requiresBatteryNotLow: syncMode.type == SyncType.unobtrusive,
requiresCharging: syncMode.type == SyncType.unobtrusive,
requiresDeviceIdle: syncMode.type == SyncType.unobtrusive,
);
if (Platform.isIOS) {
await Workmanager().registerOneOffTask(
moneroSyncTaskKey,
moneroSyncTaskKey,
initialDelay: syncMode.frequency,
existingWorkPolicy: ExistingWorkPolicy.replace,
inputData: inputData,
constraints: constraints,
);
return;
}
await Workmanager().registerPeriodicTask(
moneroSyncTaskKey,
moneroSyncTaskKey,
initialDelay: syncMode.frequency,
frequency: syncMode.frequency,
existingWorkPolicy: changeExisting ? ExistingWorkPolicy.replace : ExistingWorkPolicy.keep,
inputData: inputData,
constraints: constraints,
);
} catch (error, stackTrace) {
printV(error);
printV(stackTrace);
}
}
void cancelSyncTask() {
try {
Workmanager().cancelByUniqueName(moneroSyncTaskKey);
} catch (error, stackTrace) {
printV(error);
printV(stackTrace);
}
}
}
-3
View File
@@ -1,7 +1,6 @@
import 'package:cake_wallet/di.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/entities/background_tasks.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cake_wallet/core/wallet_loading_service.dart';
@@ -26,6 +25,4 @@ Future<void> loadCurrentWallet({String? password}) async {
name,
password: password);
await appStore.changeCurrentWallet(wallet);
getIt.get<BackgroundTasks>().registerSyncTask();
}
+41 -3
View File
@@ -1,9 +1,11 @@
import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:cake_wallet/anonpay/anonpay_invoice_info.dart';
import 'package:cake_wallet/app_scroll_behavior.dart';
import 'package:cake_wallet/buy/order.dart';
import 'package:cake_wallet/core/auth_service.dart';
import 'package:cake_wallet/core/background_sync.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/entities/contact.dart';
import 'package:cake_wallet/entities/default_settings_migration.dart';
@@ -34,11 +36,13 @@ import 'package:cw_core/hive_type_ids.dart';
import 'package:cw_core/mweb_utxo.dart';
import 'package:cw_core/node.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_daemon/flutter_daemon.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:hive/hive.dart';
import 'package:cw_core/root_dir.dart';
@@ -68,6 +72,7 @@ Future<void> runAppWithZone({Key? topLevelKey}) async {
return true;
};
await FlutterDaemon().unmarkBackgroundSync();
await initializeAppAtRoot();
if (kDebugMode) {
@@ -100,7 +105,7 @@ Future<void> initializeAppAtRoot({bool reInitializing = false}) async {
await initializeAppConfigs();
}
Future<void> initializeAppConfigs() async {
Future<void> initializeAppConfigs({bool loadWallet = true}) async {
setRootDirFromEnv();
final appDir = await getAppDir();
CakeHive.init(appDir.path);
@@ -200,6 +205,7 @@ Future<void> initializeAppConfigs() async {
encryptionKey: havenSeedStoreBoxKey);
await initialSetup(
loadWallet: loadWallet,
sharedPreferences: await SharedPreferences.getInstance(),
nodes: nodes,
powNodes: powNodes,
@@ -220,7 +226,8 @@ Future<void> initializeAppConfigs() async {
}
Future<void> initialSetup(
{required SharedPreferences sharedPreferences,
{required bool loadWallet,
required SharedPreferences sharedPreferences,
required Box<Node> nodes,
required Box<Node> powNodes,
required Box<WalletInfo> walletInfoSource,
@@ -262,7 +269,7 @@ Future<void> initialSetup(
navigatorKey: navigatorKey,
secureStorage: secureStorage,
);
await bootstrap(navigatorKey);
await bootstrap(navigatorKey, loadWallet: loadWallet);
}
class App extends StatefulWidget {
@@ -390,3 +397,34 @@ class TopLevelErrorWidget extends StatelessWidget {
);
}
}
@pragma('vm:entry-point')
Future<void> backgroundSync() async {
bool shouldUnmark = false;
try {
printV("Background sync triggered");
printV("- WidgetsFlutterBinding.ensureInitialized()");
WidgetsFlutterBinding.ensureInitialized();
printV("- DartPluginRegistrant.ensureInitialized()");
DartPluginRegistrant.ensureInitialized();
printV("- FlutterDaemon.markBackgroundSync()");
final val = await FlutterDaemon().markBackgroundSync();
if (val) {
printV("Background sync already in progress");
return;
}
shouldUnmark = true;
printV("Starting background sync");
final backgroundSync = BackgroundSync();
await initializeAppConfigs(loadWallet: false);
await backgroundSync.sync();
printV("Background sync completed");
} finally {
if (shouldUnmark) {
printV("Unmarking background sync");
await FlutterDaemon().unmarkBackgroundSync();
} else {
printV("Not unmarking background sync");
}
}
}
+4 -2
View File
@@ -15,7 +15,7 @@ import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/store/authentication_store.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
Future<void> bootstrap(GlobalKey<NavigatorState> navigatorKey) async {
Future<void> bootstrap(GlobalKey<NavigatorState> navigatorKey, {required bool loadWallet}) async {
final appStore = getIt.get<AppStore>();
final authenticationStore = getIt.get<AuthenticationStore>();
final settingsStore = getIt.get<SettingsStore>();
@@ -27,7 +27,9 @@ Future<void> bootstrap(GlobalKey<NavigatorState> navigatorKey) async {
authenticationStore.installed();
}
startAuthenticationStateChange(authenticationStore, navigatorKey);
if (loadWallet) {
startAuthenticationStateChange(authenticationStore, navigatorKey);
}
startCurrentWalletChangeReaction(appStore, settingsStore, fiatConversionStore);
startCurrentFiatChangeReaction(appStore, settingsStore, fiatConversionStore);
startCurrentFiatApiModeChangeReaction(appStore, settingsStore, fiatConversionStore);
+10
View File
@@ -36,6 +36,7 @@ import 'package:cake_wallet/src/screens/dashboard/pages/address_page.dart';
import 'package:cake_wallet/src/screens/dashboard/pages/nft_details_page.dart';
import 'package:cake_wallet/src/screens/dashboard/pages/transactions_page.dart';
import 'package:cake_wallet/src/screens/dashboard/sign_page.dart';
import 'package:cake_wallet/src/screens/dev/monero_background_sync.dart';
import 'package:cake_wallet/src/screens/disclaimer/disclaimer_page.dart';
import 'package:cake_wallet/src/screens/exchange/exchange_page.dart';
import 'package:cake_wallet/src/screens/exchange/exchange_template_page.dart';
@@ -73,6 +74,7 @@ import 'package:cake_wallet/src/screens/seed/wallet_seed_page.dart';
import 'package:cake_wallet/src/screens/send/send_page.dart';
import 'package:cake_wallet/src/screens/send/send_template_page.dart';
import 'package:cake_wallet/src/screens/send/transaction_success_info_page.dart';
import 'package:cake_wallet/src/screens/settings/background_sync_page.dart';
import 'package:cake_wallet/src/screens/settings/connection_sync_page.dart';
import 'package:cake_wallet/src/screens/settings/desktop_settings/desktop_settings_page.dart';
import 'package:cake_wallet/src/screens/settings/display_settings_page.dart';
@@ -824,6 +826,14 @@ Route<dynamic> createRoute(RouteSettings settings) {
case Routes.exchangeTradeExternalSendPage:
return MaterialPageRoute<void>(builder: (_) => getIt.get<ExchangeTradeExternalSendPage>(),);
case Routes.backgroundSync:
return CupertinoPageRoute<void>(
fullscreenDialog: true, builder: (_) => getIt.get<BackgroundSyncPage>());
case Routes.devMoneroBackgroundSync:
return MaterialPageRoute<void>(
builder: (_) => getIt.get<DevMoneroBackgroundSyncPage>(),
);
default:
return MaterialPageRoute<void>(
builder: (_) => Scaffold(
+2
View File
@@ -110,6 +110,8 @@ class Routes {
static const nftDetailsPage = '/nft_details_page';
static const importNFTPage = '/import_nft_page';
static const torPage = '/tor_page';
static const backgroundSync = '/background_sync';
static const devMoneroBackgroundSync = '/dev/monero_background_sync';
static const signPage = '/sign_page';
static const connectDevices = '/device/connect';
@@ -0,0 +1,112 @@
import 'package:cake_wallet/src/screens/base_page.dart';
import 'package:cake_wallet/src/widgets/primary_button.dart';
import 'package:cake_wallet/view_model/dev/monero_background_sync.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
class DevMoneroBackgroundSyncPage extends BasePage {
final DevMoneroBackgroundSync viewModel;
DevMoneroBackgroundSyncPage(this.viewModel);
@override
String? get title => "[dev] xmr background sync";
Widget _buildSingleCell(String title, String value) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8),
),
padding: const EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(title, style: TextStyle(fontWeight: FontWeight.bold)),
Text(value, maxLines: 1, overflow: TextOverflow.ellipsis),
],
),
);
}
@override
Widget body(BuildContext context) {
return Observer(
builder: (_) {
return GridView.count(
padding: const EdgeInsets.all(16),
crossAxisCount: 2,
childAspectRatio: 25/9,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
children: [
_buildSingleCell('Height (local)', viewModel.localBlockHeight ?? ''),
_buildSingleCell('Height (node)', viewModel.nodeBlockHeight ?? ''),
_buildSingleCell('Time', viewModel.tick.toString()),
_buildSingleCell('Background Sync', viewModel.isBackgroundSyncing ? 'Enabled' : 'Disabled'),
_buildSingleCell('Public View Key', viewModel.publicViewKey ?? ''),
_buildSingleCell('Private View Key', viewModel.privateViewKey ?? ''),
_buildSingleCell('Public Spend Key', viewModel.publicSpendKey ?? ''),
_buildSingleCell('Private Spend Key', viewModel.privateSpendKey ?? ''),
_buildSingleCell('Primary Address', viewModel.primaryAddress ?? ''),
_buildSingleCell('Passphrase', viewModel.passphrase ?? ''),
_buildSingleCell('Seed', viewModel.seed ?? ''),
_buildSingleCell('Seed Legacy', viewModel.seedLegacy ?? ''),
_enableBackgroundSyncButton(),
_disableBackgroundSyncButton(),
_refreshButton(),
_manualRescanButton(),
],
);
},
);
}
PrimaryButton _enableBackgroundSyncButton() {
return PrimaryButton(
text: "Enable background sync",
color: Colors.purple,
textColor: Colors.white,
onPressed: () {
viewModel.startBackgroundSync();
},
);
}
PrimaryButton _disableBackgroundSyncButton() {
return PrimaryButton(
text: "Disable background sync",
color: Colors.purple,
textColor: Colors.white,
onPressed: () {
viewModel.stopBackgroundSync();
},
);
}
PrimaryButton _refreshButton() {
return PrimaryButton(
text: viewModel.refreshTimer == null ? "Enable refresh" : "Disable refresh",
color: Colors.purple,
textColor: Colors.white,
onPressed: () {
if (viewModel.refreshTimer == null) {
viewModel.startRefreshTimer();
} else {
viewModel.stopRefreshTimer();
}
},
);
}
PrimaryButton _manualRescanButton() {
return PrimaryButton(
text: "Manual rescan",
color: Colors.purple,
textColor: Colors.white,
onPressed: () {
viewModel.manualRescan();
},
);
}
}
@@ -0,0 +1,91 @@
import 'dart:async';
import 'dart:io';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/src/screens/base_page.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_picker_cell.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart';
import 'package:cake_wallet/src/widgets/alert_with_no_action.dart.dart';
import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cake_wallet/view_model/dashboard/dashboard_view_model.dart';
import 'package:cake_wallet/view_model/settings/sync_mode.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
class BackgroundSyncPage extends BasePage {
BackgroundSyncPage(this.dashboardViewModel);
@override
String get title => S.current.background_sync;
final DashboardViewModel dashboardViewModel;
@override
Widget body(BuildContext context) {
return Container(
padding: EdgeInsets.only(top: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (dashboardViewModel.hasBatteryOptimization)
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.unrestricted_background_service,
value: !dashboardViewModel.batteryOptimizationEnabled,
onValueChange: (_, bool value) {
dashboardViewModel.disableBatteryOptimization();
},
);
}),
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.background_sync,
value: dashboardViewModel.backgroundSyncEnabled,
onValueChange: (dashboardViewModel.batteryOptimizationEnabled && dashboardViewModel.hasBatteryOptimization) ? (_, bool value) {
unawaited(showPopUp(context: context, builder: (context) => AlertWithOneAction(
alertTitle: S.current.background_sync,
alertContent: S.current.unrestricted_background_service_notice,
buttonText: S.current.ok,
buttonAction: () => Navigator.of(context).pop(),
)));
} : (_, bool value) {
if (value) {
dashboardViewModel.enableBackgroundSync();
} else {
dashboardViewModel.disableBackgroundSync();
}
},
);
}),
Observer(builder: (context) {
return SettingsPickerCell<SyncMode>(
title: S.current.background_sync_mode,
items: SyncMode.all,
displayItem: (SyncMode syncMode) => syncMode.name,
selectedItem: dashboardViewModel.settingsStore.currentSyncMode,
onItemSelected: (dashboardViewModel.batteryOptimizationEnabled && dashboardViewModel.hasBatteryOptimization) ? null : (syncMode) async {
dashboardViewModel.setSyncMode(syncMode);
});
}),
// Observer(builder: (context) {
// return SettingsSwitcherCell(
// title: S.current.background_sync_on_battery,
// value: dashboardViewModel.backgroundSyncOnBattery,
// onValueChange: (_, bool value) =>
// dashboardViewModel.setBackgroundSyncOnBattery(value),
// );
// }),
// Observer(builder: (context) {
// return SettingsSwitcherCell(
// title: S.current.background_sync_on_data,
// value: dashboardViewModel.backgroundSyncOnData,
// onValueChange: (_, bool value) => dashboardViewModel.setBackgroundSyncOnData(value),
// );
// }),
],
),
);
}
}
@@ -44,56 +44,17 @@ class ConnectionSyncPage extends BasePage {
: S.current.rescan,
handler: (context) => Navigator.of(context).pushNamed(Routes.rescan),
),
if (DeviceInfo.instance.isMobile && FeatureFlag.isBackgroundSyncEnabled) ...[
Observer(builder: (context) {
return SettingsPickerCell<SyncMode>(
title: S.current.background_sync_mode,
items: SyncMode.all,
displayItem: (SyncMode syncMode) => syncMode.name,
selectedItem: dashboardViewModel.syncMode,
onItemSelected: (syncMode) async {
dashboardViewModel.setSyncMode(syncMode);
if (Platform.isIOS) return;
if (syncMode.type != SyncType.disabled) {
final isDisabled = await isBatteryOptimizationDisabled();
if (isDisabled) return;
await showPopUp<void>(
context: context,
builder: (BuildContext dialogContext) {
return AlertWithTwoActions(
alertTitle: S.current.disableBatteryOptimization,
alertContent: S.current.disableBatteryOptimizationDescription,
leftButtonText: S.of(context).cancel,
rightButtonText: S.of(context).ok,
actionLeftButton: () => Navigator.of(dialogContext).pop(),
actionRightButton: () async {
await requestDisableBatteryOptimization();
Navigator.of(dialogContext).pop();
},
);
},
);
}
});
}),
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.sync_all_wallets,
value: dashboardViewModel.syncAll,
onValueChange: (_, bool value) => dashboardViewModel.setSyncAll(value),
);
}),
],
],
SettingsCellWithArrow(
title: S.current.manage_nodes,
handler: (context) => Navigator.of(context).pushNamed(Routes.manageNodes),
),
if (dashboardViewModel.hasBackgroundSync && Platform.isAndroid && FeatureFlag.isBackgroundSyncEnabled) ...[
SettingsCellWithArrow(
title: S.current.background_sync,
handler: (context) => Navigator.of(context).pushNamed(Routes.backgroundSync),
),
],
Observer(
builder: (context) {
if (!dashboardViewModel.hasPowNodes) return const SizedBox();
@@ -10,6 +10,7 @@ import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.
import 'package:cake_wallet/src/screens/settings/widgets/settings_version_cell.dart';
import 'package:cake_wallet/view_model/settings/other_settings_view_model.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
@@ -63,6 +64,12 @@ class OtherSettingsPage extends BasePage {
handler: (BuildContext context) =>
Navigator.of(context).pushNamed(Routes.readDisclaimer),
),
if (kDebugMode && _otherSettingsViewModel.walletType == WalletType.monero)
SettingsCellWithArrow(
title: '[dev] monero background sync',
handler: (BuildContext context) =>
Navigator.of(context).pushNamed(Routes.devMoneroBackgroundSync),
),
Spacer(),
SettingsVersionCell(
title: S.of(context).version(_otherSettingsViewModel.currentVersion)),
+7 -13
View File
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -8,7 +9,6 @@ import 'package:cake_wallet/core/secure_storage.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/entities/action_list_display_mode.dart';
import 'package:cake_wallet/entities/auto_generate_subaddress_status.dart';
import 'package:cake_wallet/entities/background_tasks.dart';
import 'package:cake_wallet/entities/balance_display_mode.dart';
import 'package:cake_wallet/entities/cake_2fa_preset_options.dart';
import 'package:cake_wallet/entities/country.dart';
@@ -46,6 +46,7 @@ import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_daemon/flutter_daemon.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -57,7 +58,6 @@ class SettingsStore = SettingsStoreBase with _$SettingsStore;
abstract class SettingsStoreBase with Store {
SettingsStoreBase(
{required SecureStorage secureStorage,
required BackgroundTasks backgroundTasks,
required SharedPreferences sharedPreferences,
required bool initialShouldShowMarketPlaceInDashboard,
required bool initialShowAddressBookPopupEnabled,
@@ -146,7 +146,6 @@ abstract class SettingsStoreBase with Store {
powNodes = ObservableMap<WalletType, Node>.of(powNodes),
_secureStorage = secureStorage,
_sharedPreferences = sharedPreferences,
_backgroundTasks = backgroundTasks,
fiatCurrency = initialFiatCurrency,
balanceDisplayMode = initialBalanceDisplayMode,
shouldSaveRecipientAddress = initialSaveRecipientAddress,
@@ -303,11 +302,11 @@ abstract class SettingsStoreBase with Store {
PreferencesKey.shouldSaveRecipientAddressKey, shouldSaveRecipientAddress));
if (DeviceInfo.instance.isMobile) {
setIsAppSecureNative(isAppSecure);
unawaited(setIsAppSecureNative(isAppSecure));
reaction((_) => isAppSecure, (bool isAppSecure) {
sharedPreferences.setBool(PreferencesKey.isAppSecureKey, isAppSecure);
setIsAppSecureNative(isAppSecure);
unawaited(setIsAppSecureNative(isAppSecure));
});
}
@@ -402,14 +401,11 @@ abstract class SettingsStoreBase with Store {
reaction((_) => currentSyncMode, (SyncMode syncMode) {
sharedPreferences.setInt(PreferencesKey.syncModeKey, syncMode.type.index);
_backgroundTasks.registerSyncTask(changeExisting: true);
FlutterDaemon().startBackgroundSync(syncMode.frequency.inMinutes);
});
reaction((_) => currentSyncAll, (bool syncAll) {
sharedPreferences.setBool(PreferencesKey.syncAllKey, syncAll);
_backgroundTasks.registerSyncTask(changeExisting: true);
});
reaction(
@@ -807,6 +803,7 @@ abstract class SettingsStoreBase with Store {
@observable
bool lookupsWellKnown;
@observable
SyncMode currentSyncMode;
@@ -843,7 +840,6 @@ abstract class SettingsStoreBase with Store {
final SecureStorage _secureStorage;
final SharedPreferences _sharedPreferences;
final BackgroundTasks _backgroundTasks;
ObservableMap<WalletType, Node> nodes;
ObservableMap<WalletType, Node> powNodes;
@@ -885,7 +881,6 @@ abstract class SettingsStoreBase with Store {
ThemeBase? initialTheme}) async {
final sharedPreferences = await getIt.getAsync<SharedPreferences>();
final secureStorage = await getIt.get<SecureStorage>();
final backgroundTasks = getIt.get<BackgroundTasks>();
final currentFiatCurrency = FiatCurrency.deserialize(
raw: sharedPreferences.getString(PreferencesKey.currentFiatCurrencyKey)!);
final savedCakePayCountryRaw = sharedPreferences.getString(PreferencesKey.currentCakePayCountry);
@@ -1157,7 +1152,7 @@ abstract class SettingsStoreBase with Store {
}
final savedSyncMode = SyncMode.all.firstWhere((element) {
return element.type.index == (sharedPreferences.getInt(PreferencesKey.syncModeKey) ?? 0);
return element.type.index == (sharedPreferences.getInt(PreferencesKey.syncModeKey) ?? 2); // default to 2 - daily sync
});
final savedSyncAll = sharedPreferences.getBool(PreferencesKey.syncAllKey) ?? true;
@@ -1339,7 +1334,6 @@ abstract class SettingsStoreBase with Store {
shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
initialEthereumTransactionPriority: ethereumTransactionPriority,
initialPolygonTransactionPriority: polygonTransactionPriority,
backgroundTasks: backgroundTasks,
initialSyncMode: savedSyncMode,
initialSyncAll: savedSyncAll,
shouldShowYatPopup: shouldShowYatPopup,
+1 -1
View File
@@ -4,6 +4,6 @@ class FeatureFlag {
static const bool isCakePayEnabled = false;
static const bool isExolixEnabled = true;
static const bool isInAppTorEnabled = false;
static const bool isBackgroundSyncEnabled = false;
static const bool isBackgroundSyncEnabled = true;
static const int verificationWordsCount = kDebugMode ? 0 : 2;
}
@@ -4,6 +4,7 @@ import 'dart:io' show Platform;
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/background_sync.dart';
import 'package:cake_wallet/core/key_service.dart';
import 'package:cake_wallet/entities/auto_generate_subaddress_status.dart';
import 'package:cake_wallet/entities/balance_display_mode.dart';
@@ -40,12 +41,14 @@ import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/utils/file.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:eth_sig_util/util/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_daemon/flutter_daemon.dart';
import 'package:http/http.dart' as http;
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -175,6 +178,8 @@ abstract class DashboardViewModelBase with Store {
isShowFirstYatIntroduction = false;
isShowSecondYatIntroduction = false;
isShowThirdYatIntroduction = false;
unawaited(isBackgroundSyncEnabled());
unawaited(isBatteryOptimizationEnabled());
final _wallet = wallet;
@@ -406,6 +411,11 @@ abstract class DashboardViewModelBase with Store {
@computed
bool get hasRescan => wallet.hasRescan;
@computed
bool get hasBackgroundSync => [
WalletType.monero,
].contains(wallet.type);
@computed
bool get isMoneroViewOnly {
if (wallet.type != WalletType.monero) return false;
@@ -492,6 +502,69 @@ abstract class DashboardViewModelBase with Store {
@observable
late bool showDecredInfoCard;
@observable
bool backgroundSyncEnabled = false;
@action
Future<bool> isBackgroundSyncEnabled() async {
if (!Platform.isAndroid) {
return false;
}
final resp = await FlutterDaemon().getBackgroundSyncStatus();
backgroundSyncEnabled = resp;
return resp;
}
bool get hasBatteryOptimization => Platform.isAndroid;
@observable
bool batteryOptimizationEnabled = false;
@action
Future<bool> isBatteryOptimizationEnabled() async {
if (!hasBatteryOptimization) {
return false;
}
final resp = await FlutterDaemon().isBatteryOptimizationDisabled();
batteryOptimizationEnabled = !resp;
if (batteryOptimizationEnabled && await isBackgroundSyncEnabled()) {
// If the battery optimization is enabled, we need to disable the background sync
await disableBackgroundSync();
}
return resp;
}
@action
Future<void> disableBatteryOptimization() async {
final resp = await FlutterDaemon().requestDisableBatteryOptimization();
unawaited((() async {
// android doesn't return if the permission was granted, so we need to poll it,
// minute should be enough for the fallback method (opening settings and changing the permission)
for (var i = 0; i < 4 * 60; i++) {
await Future.delayed(Duration(milliseconds: 250));
await isBatteryOptimizationEnabled();
}
})());
}
@action
Future<void> enableBackgroundSync() async {
if (hasBatteryOptimization && batteryOptimizationEnabled) {
disableBackgroundSync();
return;
}
final resp = await FlutterDaemon().startBackgroundSync(settingsStore.currentSyncMode.frequency.inMinutes);
printV("Background sync enabled: $resp");
backgroundSyncEnabled = true;
}
@action
Future<void> disableBackgroundSync() async {
final resp = await FlutterDaemon().stopBackgroundSync();
printV("Background sync disabled: $resp");
backgroundSyncEnabled = false;
}
@computed
bool get hasEnabledMwebBefore => settingsStore.hasEnabledMwebBefore;
@@ -797,11 +870,11 @@ abstract class DashboardViewModelBase with Store {
}
}
@computed
SyncMode get syncMode => settingsStore.currentSyncMode;
@action
void setSyncMode(SyncMode syncMode) => settingsStore.currentSyncMode = syncMode;
Future<void> setSyncMode(SyncMode syncMode) async {
settingsStore.currentSyncMode = syncMode;
await enableBackgroundSync();
}
@computed
bool get syncAll => settingsStore.currentSyncAll;
@@ -0,0 +1,106 @@
import 'dart:async';
import 'package:cake_wallet/core/key_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cw_monero/monero_wallet.dart';
import 'package:mobx/mobx.dart';
import 'package:cw_core/wallet_base.dart';
part 'monero_background_sync.g.dart';
class DevMoneroBackgroundSync = DevMoneroBackgroundSyncBase with _$DevMoneroBackgroundSync;
abstract class DevMoneroBackgroundSyncBase with Store {
DevMoneroBackgroundSyncBase(WalletBase wallet) : wallet = wallet;
final WalletBase wallet;
@observable
Timer? refreshTimer;
@observable
String? localBlockHeight;
@observable
String? nodeBlockHeight;
@observable
String? primaryAddress;
@observable
String? publicViewKey;
@observable
String? privateViewKey;
@observable
String? publicSpendKey;
@observable
String? privateSpendKey;
@observable
String? passphrase;
@observable
String? seed;
@observable
String? seedLegacy;
@observable
int tick = -1;
@observable
bool isBackgroundSyncing = false;
Future<void> _setValues() async {
final w = (wallet as MoneroWallet);
localBlockHeight = (await monero!.getCurrentHeight()).toString();
nodeBlockHeight = (await w.getNodeHeight()).toString();
final keys = w.keys;
primaryAddress = keys.primaryAddress;
publicViewKey = keys.publicViewKey;
privateViewKey = keys.privateViewKey;
publicSpendKey = keys.publicSpendKey;
privateSpendKey = keys.privateSpendKey;
passphrase = keys.passphrase;
seed = w.seed;
seedLegacy = w.seedLegacy("English");
tick = refreshTimer?.tick ?? -1;
isBackgroundSyncing = w.isBackgroundSyncRunning;
}
@action
Future<void> manualRescan() async {
final w = (wallet as MoneroWallet);
await wallet.rescan(height: await w.getNodeHeight() - 10000);
}
@action
void startRefreshTimer() {
refreshTimer = Timer.periodic(Duration(seconds: 1), (timer) async {
await _setValues();
});
}
@action
void stopRefreshTimer() {
refreshTimer?.cancel();
refreshTimer = null;
}
@action
void startBackgroundSync() {
final w = (wallet as MoneroWallet);
w.startBackgroundSync();
}
@action
Future<void> stopBackgroundSync() async {
final w = (wallet as MoneroWallet);
final keyService = getIt.get<KeyService>();
await w.stopBackgroundSync(await keyService.getWalletPassword(walletName: wallet.name));
}
}
+6 -4
View File
@@ -1,4 +1,4 @@
enum SyncType { disabled, unobtrusive, aggressive }
enum SyncType { aggresive, hourly, daily }
class SyncMode {
SyncMode(this.name, this.type, this.frequency);
@@ -8,8 +8,10 @@ class SyncMode {
final Duration frequency;
static final all = [
SyncMode("Disabled", SyncType.disabled, Duration.zero),
SyncMode("Unobtrusive", SyncType.unobtrusive, Duration(hours: 12)),
SyncMode("Aggressive", SyncType.aggressive, Duration(hours: 3)),
// **Technically** we could call aggressive option "15 minutes" but OS may "not feel like it",
// so instead we will call it aggressive so user knows that it will be as frequent as possible.
SyncMode("Aggressive", SyncType.aggresive, Duration(minutes: 15)),
SyncMode("Hourly", SyncType.hourly, Duration(hours: 1)),
SyncMode("Daily", SyncType.daily, Duration(hours: 18)), // yes this is straight up lie.
];
}
-2
View File
@@ -2,7 +2,6 @@ import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/entities/background_tasks.dart';
import 'package:cake_wallet/entities/generate_name.dart';
import 'package:cake_wallet/entities/hash_wallet_identifier.dart';
import 'package:cake_wallet/generated/i18n.dart';
@@ -113,7 +112,6 @@ abstract class WalletCreationVMBase with Store {
walletInfo.address = wallet.walletAddresses.address;
await _walletInfoSource.add(walletInfo);
await _appStore.changeCurrentWallet(wallet);
getIt.get<BackgroundTasks>().registerSyncTask();
_appStore.authenticationStore.allowedCreate();
state = ExecutedSuccessfullyState();
} catch (e, s) {
@@ -158,6 +158,7 @@ abstract class WalletGroupsDisplayViewModelBase with Store {
isCurrent: info.name == _appStore.wallet?.name && info.type == _appStore.wallet?.type,
isEnabled: availableWalletTypes.contains(info.type),
isTestnet: info.network?.toLowerCase().contains('testnet') ?? false,
isHardware: info.isHardwareWallet,
);
}
}
@@ -5,6 +5,7 @@ class WalletListItem {
required this.name,
required this.type,
required this.key,
required this.isHardware,
this.isCurrent = false,
this.isEnabled = true,
this.isTestnet = false,
@@ -16,4 +17,5 @@ class WalletListItem {
final dynamic key;
final bool isEnabled;
final bool isTestnet;
final bool isHardware;
}
@@ -265,6 +265,7 @@ abstract class WalletListViewModelBase with Store {
info.type == _appStore.wallet?.type,
isEnabled: availableWalletTypes.contains(info.type),
isTestnet: info.network?.toLowerCase().contains('testnet') ?? false,
isHardware: info.isHardwareWallet,
);
}
}