cake_wallet/lib/entities/background_tasks.dart

516 lines
18 KiB
Dart
Raw Normal View History

2024-07-25 16:38:12 +00:00
import 'dart:async';
import 'dart:io';
2024-08-29 18:29:37 +00:00
import 'dart:ui';
import 'package:cake_wallet/core/sync_status_title.dart';
2024-09-04 16:15:01 +00:00
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cake_wallet/generated/i18n.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';
2024-09-04 16:15:01 +00:00
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';
2024-09-12 04:03:47 +00:00
import 'package:cw_bitcoin/electrum_wallet.dart';
import 'package:cw_core/sync_status.dart';
2024-09-04 16:15:01 +00:00
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
2024-08-29 18:29:37 +00:00
import 'package:flutter/widgets.dart';
2024-08-28 18:54:47 +00:00
import 'package:flutter_background_service/flutter_background_service.dart';
2024-08-29 18:29:37 +00:00
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:cake_wallet/main.dart';
import 'package:cake_wallet/di.dart';
2024-09-18 19:34:27 +00:00
import 'package:intl/intl.dart';
const moneroSyncTaskKey = "com.fotolockr.cakewallet.monero_sync_task";
2024-07-24 22:21:52 +00:00
const mwebSyncTaskKey = "com.fotolockr.cakewallet.mweb_sync_task";
2024-09-03 21:31:02 +00:00
const initialNotificationTitle = 'Cake Background Sync';
const standbyMessage = 'On standby - app is in the foreground';
const readyMessage = 'Ready to sync - waiting until the app has been in the background for a while';
2024-09-18 20:04:56 +00:00
const startMessage = 'Starting sync - app is in the background';
2024-09-03 21:31:02 +00:00
const notificationId = 888;
const notificationChannelId = 'cake_service';
2024-09-03 21:50:06 +00:00
const notificationChannelName = 'CAKE BACKGROUND SERVICE';
2024-09-03 21:31:02 +00:00
const notificationChannelDescription = 'Cake Wallet Background Service';
2024-09-03 21:50:06 +00:00
const DELAY_SECONDS_BEFORE_SYNC_START = 15;
2024-09-17 19:35:25 +00:00
const spNodeNotificationMessage =
"Currently configured Bitcoin node does not support Silent Payments. skipping wallet";
2024-09-18 18:32:01 +00:00
const SYNC_THRESHOLD = 0.98;
2024-09-18 20:04:56 +00:00
const REFRESH_QUEUE_HOURS = 1;
2024-09-17 19:35:25 +00:00
void setMainNotification(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin, {
required String title,
required String content,
}) async {
2024-09-03 21:31:02 +00:00
flutterLocalNotificationsPlugin.show(
notificationId,
2024-09-17 19:35:25 +00:00
title,
content,
const NotificationDetails(
android: AndroidNotificationDetails(
notificationChannelId,
notificationChannelName,
icon: 'ic_bg_service_small',
ongoing: true,
2024-09-17 21:20:14 +00:00
silent: true,
),
),
);
}
2024-09-17 19:35:25 +00:00
void setNotificationStandby(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
flutterLocalNotificationsPlugin.cancelAll();
2024-09-17 19:35:25 +00:00
setMainNotification(
flutterLocalNotificationsPlugin,
title: initialNotificationTitle,
content: standbyMessage,
2024-09-03 21:31:02 +00:00
);
2024-08-29 18:29:37 +00:00
}
2024-09-17 19:35:25 +00:00
void setNotificationReady(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
2024-09-16 20:46:48 +00:00
flutterLocalNotificationsPlugin.cancelAll();
2024-09-17 19:35:25 +00:00
setMainNotification(
flutterLocalNotificationsPlugin,
title: initialNotificationTitle,
content: readyMessage,
);
}
2024-09-24 19:18:38 +00:00
void setNotificationStarting(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
2024-09-18 20:04:56 +00:00
flutterLocalNotificationsPlugin.cancelAll();
setMainNotification(
flutterLocalNotificationsPlugin,
title: initialNotificationTitle,
content: startMessage,
);
}
2024-09-18 02:31:11 +00:00
void setWalletNotification(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
{required String title, required String content, required int walletNum}) async {
2024-09-16 20:46:48 +00:00
flutterLocalNotificationsPlugin.show(
2024-09-17 19:35:25 +00:00
notificationId + walletNum,
2024-09-18 02:31:11 +00:00
title,
content,
2024-09-17 19:35:25 +00:00
NotificationDetails(
2024-09-16 20:46:48 +00:00
android: AndroidNotificationDetails(
2024-09-17 19:35:25 +00:00
"${notificationChannelId}_$walletNum",
"${notificationChannelName}_$walletNum",
2024-09-16 20:46:48 +00:00
icon: 'ic_bg_service_small',
2024-09-18 02:31:11 +00:00
ongoing: true,
2024-09-17 21:20:14 +00:00
silent: true,
2024-09-16 20:46:48 +00:00
),
),
);
}
2024-08-29 18:29:37 +00:00
@pragma('vm:entry-point')
Future<void> onStart(ServiceInstance service) async {
2024-09-17 19:35:25 +00:00
print("BACKGROUND SERVICE STARTED");
2024-09-03 21:31:02 +00:00
bool bgSyncStarted = false;
Timer? _syncTimer;
2024-09-24 19:18:38 +00:00
Timer? _stuckSyncTimer;
2024-09-18 18:32:01 +00:00
Timer? _queueTimer;
2024-08-29 18:29:37 +00:00
2024-08-29 21:53:10 +00:00
// commented because the behavior appears to be bugged:
// DartPluginRegistrant.ensureInitialized();
2024-08-29 18:29:37 +00:00
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
2024-09-03 21:31:02 +00:00
service.on('stopService').listen((event) async {
2024-09-17 19:35:25 +00:00
print("STOPPING BACKGROUND SERVICE");
2024-09-03 21:31:02 +00:00
_syncTimer?.cancel();
await service.stopSelf();
2024-08-29 18:29:37 +00:00
});
service.on('status').listen((event) async {
print(event);
});
2024-09-03 21:31:02 +00:00
service.on('setForeground').listen((event) async {
2024-08-29 21:53:10 +00:00
bgSyncStarted = false;
2024-09-03 21:31:02 +00:00
_syncTimer?.cancel();
2024-09-03 21:50:06 +00:00
setNotificationStandby(flutterLocalNotificationsPlugin);
2024-08-29 21:53:10 +00:00
});
service.on('setReady').listen((event) async {
setNotificationReady(flutterLocalNotificationsPlugin);
});
2024-09-03 21:31:02 +00:00
// we have entered the background, start the sync:
service.on('setBackground').listen((event) async {
2024-08-29 18:29:37 +00:00
if (bgSyncStarted) {
return;
}
2024-08-29 18:29:37 +00:00
bgSyncStarted = true;
2024-09-03 21:31:02 +00:00
2024-09-03 21:50:06 +00:00
await Future.delayed(const Duration(seconds: DELAY_SECONDS_BEFORE_SYNC_START));
2024-09-17 19:35:25 +00:00
print("STARTING SYNC FROM BG");
2024-09-18 20:04:56 +00:00
setNotificationStarting(flutterLocalNotificationsPlugin);
2024-08-29 18:29:37 +00:00
2024-09-03 21:31:02 +00:00
try {
2024-09-11 21:25:00 +00:00
await initializeAppConfigs(loadWallet: false);
2024-09-03 21:31:02 +00:00
} catch (_) {
2024-09-03 21:50:06 +00:00
// these errors still show up in logs which doesn't really make sense to me
2024-09-03 21:31:02 +00:00
}
2024-08-29 18:29:37 +00:00
print("INITIALIZED APP CONFIGS");
2024-08-29 18:29:37 +00:00
2024-09-17 19:35:25 +00:00
// final currentWallet = getIt.get<AppStore>().wallet;
// // don't start syncing immediately:
// await currentWallet?.stopSync();
2024-09-04 16:15:01 +00:00
final walletLoadingService = getIt.get<WalletLoadingService>();
2024-09-11 16:57:45 +00:00
final settingsStore = getIt.get<SettingsStore>();
final walletListViewModel = getIt.get<WalletListViewModel>();
2024-09-04 16:15:01 +00:00
2024-09-18 18:32:01 +00:00
List<WalletBase> syncingWallets = [];
List<WalletBase> standbyWallets = [];
2024-09-04 16:15:01 +00:00
2024-09-18 18:32:01 +00:00
// get all Monero / Wownero wallets and add them
2024-09-17 19:35:25 +00:00
final List<WalletListItem> moneroWallets = walletListViewModel.wallets
.where((element) => [WalletType.monero, WalletType.wownero].contains(element.type))
.toList();
for (int i = 0; i < moneroWallets.length; i++) {
final wallet = await walletLoadingService.load(moneroWallets[i].type, moneroWallets[i].name);
final node = settingsStore.getCurrentNode(moneroWallets[i].type);
2024-09-18 18:32:01 +00:00
await wallet.stopSync();
2024-09-17 19:35:25 +00:00
syncingWallets.add(wallet);
}
2024-09-04 16:15:01 +00:00
2024-09-18 18:32:01 +00:00
// get all litecoin wallets and add them:
2024-09-17 19:35:25 +00:00
final List<WalletListItem> litecoinWallets = walletListViewModel.wallets
.where((element) => element.type == WalletType.litecoin)
.toList();
// we only need to sync the first litecoin wallet since they share the same collection of blocks
if (litecoinWallets.isNotEmpty) {
try {
final firstWallet = litecoinWallets.first;
final wallet = await walletLoadingService.load(firstWallet.type, firstWallet.name);
2024-09-18 18:32:01 +00:00
await wallet.stopSync();
2024-09-04 16:15:01 +00:00
syncingWallets.add(wallet);
2024-09-17 19:35:25 +00:00
} catch (e) {
// couldn't connect to mwebd (most likely)
print("error syncing litecoin wallet: $e");
2024-09-04 16:15:01 +00:00
}
2024-09-17 19:35:25 +00:00
}
2024-09-04 16:15:01 +00:00
2024-09-18 18:32:01 +00:00
// get all bitcoin wallets and add them:
2024-09-17 19:35:25 +00:00
final List<WalletListItem> bitcoinWallets =
walletListViewModel.wallets.where((element) => element.type == WalletType.bitcoin).toList();
bool spSupported = true;
for (int i = 0; i < bitcoinWallets.length; i++) {
try {
if (!spSupported) continue;
final wallet =
await walletLoadingService.load(bitcoinWallets[i].type, bitcoinWallets[i].name);
final node = settingsStore.getCurrentNode(WalletType.bitcoin);
await wallet.connectToNode(node: node);
2024-09-17 19:35:25 +00:00
bool nodeSupportsSP = await (wallet as ElectrumWallet).getNodeSupportsSilentPayments();
if (!nodeSupportsSP) {
print("Configured node does not support silent payments, skipping wallet");
2024-09-18 02:31:11 +00:00
setWalletNotification(
flutterLocalNotificationsPlugin,
title: initialNotificationTitle,
content: spNodeNotificationMessage,
2024-09-18 18:32:01 +00:00
walletNum: syncingWallets.length + 1,
2024-09-18 02:31:11 +00:00
);
2024-09-17 19:35:25 +00:00
spSupported = false;
continue;
}
2024-09-17 21:20:14 +00:00
2024-09-18 02:31:11 +00:00
await wallet.stopSync();
2024-09-17 23:50:30 +00:00
syncingWallets.add(wallet);
2024-09-17 19:35:25 +00:00
} catch (e) {
print("error syncing bitcoin wallet_$i: $e");
}
2024-09-04 16:15:01 +00:00
}
2024-09-12 04:03:47 +00:00
print("STARTING SYNC TIMER");
2024-09-03 21:31:02 +00:00
_syncTimer?.cancel();
2024-09-18 02:31:11 +00:00
_syncTimer = Timer.periodic(const Duration(milliseconds: 2000), (timer) async {
for (int i = 0; i < syncingWallets.length; i++) {
final wallet = syncingWallets[i];
2024-09-18 18:32:01 +00:00
final syncStatus = wallet.syncStatus;
final progress = wallet.syncStatus.progress();
final progressPercent = (progress * 100).toStringAsPrecision(5) + "%";
2024-09-17 19:35:25 +00:00
2024-09-18 18:32:01 +00:00
if (progress > 0.999) {
2024-09-17 23:50:30 +00:00
print("WALLET $i SYNCED");
2024-09-18 18:32:01 +00:00
wallet.stopSync();
// pop the first wallet from the list
standbyWallets.add(syncingWallets.removeAt(i));
2024-09-18 19:34:27 +00:00
flutterLocalNotificationsPlugin.cancelAll();
2024-09-18 02:31:11 +00:00
continue;
2024-09-17 23:50:30 +00:00
}
2024-09-18 18:32:01 +00:00
bool shouldSync = i == 0;
String title = "${walletTypeToCryptoCurrency(wallet.type).title} - ${wallet.name}";
late String content;
2024-09-18 18:32:01 +00:00
if (shouldSync) {
if (syncStatus is NotConnectedSyncStatus) {
2024-09-18 19:34:27 +00:00
print("${wallet.name} NOT CONNECTED");
2024-09-18 18:32:01 +00:00
final node = settingsStore.getCurrentNode(wallet.type);
await wallet.connectToNode(node: node);
2024-09-18 19:34:27 +00:00
wallet.startSync();
print("STARTED SYNC");
2024-09-18 18:32:01 +00:00
// wait a few seconds before checking progress
// await Future.delayed(const Duration(seconds: 10));
}
if (syncStatus is SyncingSyncStatus) {
final blocksLeft = syncStatus.blocksLeft;
2024-09-18 19:34:27 +00:00
content = "$blocksLeft Blocks Left";
2024-09-18 18:32:01 +00:00
} else if (syncStatus is SyncedSyncStatus) {
content = "Synced";
2024-09-18 18:32:01 +00:00
} else if (syncStatus is SyncedTipSyncStatus) {
final tip = syncStatus.tip;
content = "Scanned Tip: $tip";
2024-09-18 18:32:01 +00:00
} else if (syncStatus is NotConnectedSyncStatus) {
content = "Still Not Connected";
} else if (syncStatus is AttemptingSyncStatus) {
content = "Attempting Sync";
2024-09-18 18:32:01 +00:00
} else if (syncStatus is StartingScanSyncStatus) {
content = "Starting Scan";
} else if (syncStatus is SyncronizingSyncStatus) {
content = "Syncronizing";
} else if (syncStatus is FailedSyncStatus) {
content = "Failed Sync";
} else if (syncStatus is ConnectingSyncStatus) {
content = "Connecting";
} else {
throw Exception("sync type not covered");
}
2024-09-18 18:32:01 +00:00
} else {
if (syncStatus is! NotConnectedSyncStatus) {
wallet.stopSync();
}
if (progress < SYNC_THRESHOLD) {
content = "$progressPercent - Waiting in sync queue";
} else {
content = "$progressPercent - This shouldn't happen, wallet is > SYNC_THRESHOLD";
}
}
2024-09-11 19:33:11 +00:00
2024-09-18 19:34:27 +00:00
content += " - ${DateFormat("hh:mm:ss").format(DateTime.now())}";
2024-09-18 18:32:01 +00:00
setWalletNotification(
flutterLocalNotificationsPlugin,
title: title,
content: content,
walletNum: i,
);
}
for (int i = 0; i < standbyWallets.length; i++) {
int notificationIndex = syncingWallets.length + i + 1;
final wallet = standbyWallets[i];
final title = "${walletTypeToCryptoCurrency(wallet.type).title} - ${wallet.name}";
String content = "Synced - on standby until next queue refresh";
setWalletNotification(
flutterLocalNotificationsPlugin,
title: title,
content: content,
walletNum: notificationIndex,
2024-09-11 19:33:11 +00:00
);
}
2024-08-29 18:29:37 +00:00
});
2024-09-18 18:32:01 +00:00
_queueTimer?.cancel();
// add a timer that checks all wallets and adds them to the queue if they are less than SYNC_THRESHOLD synced:
2024-09-18 20:04:56 +00:00
_queueTimer = Timer.periodic(const Duration(hours: REFRESH_QUEUE_HOURS), (timer) async {
2024-09-18 18:32:01 +00:00
for (int i = 0; i < standbyWallets.length; i++) {
final wallet = standbyWallets[i];
final syncStatus = wallet.syncStatus;
// connect to the node if we haven't already:
if (syncStatus is NotConnectedSyncStatus) {
final node = settingsStore.getCurrentNode(wallet.type);
await wallet.connectToNode(node: node);
await wallet.startSync();
await Future.delayed(
const Duration(seconds: 10)); // wait a few seconds before checking progress
}
if (syncStatus.progress() < SYNC_THRESHOLD) {
syncingWallets.add(standbyWallets.removeAt(i));
}
}
});
2024-09-24 19:18:38 +00:00
// setup a watch dog to restart the sync process if it gets stuck:
List<double> lastFewProgresses = [];
_stuckSyncTimer?.cancel();
_stuckSyncTimer = Timer.periodic(const Duration(seconds: 10), (timer) async {
// TODO: finish this
// if (syncStatus is! SyncingSyncStatus) return;
// if (syncStatus.progress() > 0.98) return; // don't check if we're close to synced
// lastFewProgresses.add(syncStatus.progress());
// if (lastFewProgresses.length < 10) return;
// // limit list size to 10:
// while (lastFewProgresses.length > 10) {
// lastFewProgresses.removeAt(0);
// }
// // if the progress is the same over the last 100 seconds, restart the sync:
// if (lastFewProgresses.every((p) => p == lastFewProgresses.first)) {
// print("mweb syncing is stuck, restarting...");
// syncStatus = LostConnectionSyncStatus();
// await stopSync();
// }
});
});
}
2024-08-29 18:29:37 +00:00
@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
return true;
}
2024-08-28 18:54:47 +00:00
2024-09-11 16:57:45 +00:00
Future<void> initializeService(FlutterBackgroundService bgService, bool useNotifications) async {
if (useNotifications) {
2024-09-11 19:33:11 +00:00
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
2024-09-11 16:57:45 +00:00
FlutterLocalNotificationsPlugin();
2024-08-29 18:29:37 +00:00
2024-09-11 16:57:45 +00:00
if (Platform.isIOS || Platform.isAndroid) {
await flutterLocalNotificationsPlugin.initialize(
const InitializationSettings(
iOS: DarwinInitializationSettings(),
android: AndroidInitializationSettings('ic_bg_service_small'),
),
);
}
2024-08-29 18:29:37 +00:00
2024-09-11 19:33:11 +00:00
for (int i = 0; i < 10; i++) {
AndroidNotificationChannel channel = AndroidNotificationChannel(
"${notificationChannelId}_$i",
"${notificationChannelName}_$i",
description: notificationChannelDescription,
2024-09-17 21:20:14 +00:00
importance: Importance.min,
2024-09-11 19:33:11 +00:00
);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
}
2024-08-29 18:29:37 +00:00
2024-09-11 16:57:45 +00:00
setNotificationStandby(flutterLocalNotificationsPlugin);
}
2024-08-29 21:53:10 +00:00
2024-09-03 21:31:02 +00:00
// notify the service that we are in the foreground:
bgService.invoke("setForeground");
2024-08-29 21:53:10 +00:00
2024-08-29 21:58:07 +00:00
try {
bool isServiceRunning = await bgService.isRunning();
if (isServiceRunning) {
print("Service is ALREADY running!");
return;
}
} catch (_) {}
2024-09-12 04:03:47 +00:00
print("INITIALIZING SERVICE");
2024-08-29 18:29:37 +00:00
await bgService.configure(
2024-08-28 18:54:47 +00:00
androidConfiguration: AndroidConfiguration(
onStart: onStart,
2024-08-29 18:29:37 +00:00
autoStart: true,
isForegroundMode: true,
2024-08-29 21:53:10 +00:00
notificationChannelId: notificationChannelId,
initialNotificationTitle: initialNotificationTitle,
initialNotificationContent: standbyMessage,
2024-08-29 21:53:10 +00:00
foregroundServiceNotificationId: notificationId,
2024-08-29 18:29:37 +00:00
foregroundServiceTypes: [AndroidForegroundType.dataSync],
),
iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
onBackground: onIosBackground,
2024-08-28 18:54:47 +00:00
),
);
}
class BackgroundTasks {
2024-08-29 18:29:37 +00:00
FlutterBackgroundService bgService = FlutterBackgroundService();
2024-09-11 19:33:11 +00:00
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
2024-08-29 18:29:37 +00:00
void serviceBackground() {
bgService.invoke("setBackground");
}
Future<void> serviceForeground() async {
final settingsStore = getIt.get<SettingsStore>();
bool showNotifications = settingsStore.showSyncNotification;
bgService.invoke('stopService');
await Future.delayed(const Duration(seconds: 2));
initializeService(bgService, showNotifications);
}
void serviceReady() {
final settingsStore = getIt.get<SettingsStore>();
bool showNotifications = settingsStore.showSyncNotification;
if (showNotifications) {
bgService.invoke('setReady');
2024-09-03 21:31:02 +00:00
}
}
void registerBackgroundService() async {
print("REGISTER BACKGROUND SERVICE");
try {
final settingsStore = getIt.get<SettingsStore>();
final walletListViewModel = getIt.get<WalletListViewModel>();
bool hasMonero =
walletListViewModel.wallets.any((element) => element.type == WalletType.monero);
bool hasLitecoin =
walletListViewModel.wallets.any((element) => element.type == WalletType.litecoin);
2024-07-24 22:21:52 +00:00
bool hasBitcoin =
walletListViewModel.wallets.any((element) => element.type == WalletType.bitcoin);
2024-09-11 16:57:45 +00:00
if (!settingsStore.silentPaymentsAlwaysScan) {
hasBitcoin = false;
}
if (!settingsStore.mwebAlwaysScan) {
hasLitecoin = false;
}
/// if its not android nor ios, or the user has no monero wallets; exit
2024-09-11 16:57:45 +00:00
if (!DeviceInfo.instance.isMobile || (!hasMonero && !hasLitecoin && !hasBitcoin)) {
return;
}
final SyncMode syncMode = settingsStore.currentSyncMode;
2024-09-17 19:35:25 +00:00
final bool useNotifications = settingsStore.showSyncNotification;
2024-09-17 19:35:25 +00:00
if (useNotifications) {
2024-09-11 19:33:11 +00:00
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.requestNotificationsPermission();
}
2024-09-17 19:35:25 +00:00
bgService.invoke("stopService");
if (syncMode.type == SyncType.disabled || !FeatureFlag.isBackgroundSyncEnabled) {
return;
}
2024-08-29 18:29:37 +00:00
2024-09-17 19:35:25 +00:00
await initializeService(bgService, useNotifications);
} catch (error, stackTrace) {
print(error);
print(stackTrace);
}
}
}