cake_wallet/lib/core/backup_service.dart

558 lines
25 KiB
Dart
Raw Normal View History

2021-01-13 16:43:34 +00:00
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:cake_wallet/entities/cake_2fa_preset_options.dart';
2022-02-03 18:04:16 +00:00
import 'package:cw_core/wallet_type.dart';
2021-01-13 16:43:34 +00:00
import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:path_provider/path_provider.dart';
import 'package:cryptography/cryptography.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:archive/archive_io.dart';
import 'package:cake_wallet/core/key_service.dart';
import 'package:cake_wallet/entities/encrypt.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
import 'package:cake_wallet/entities/secret_store_key.dart';
2021-12-24 12:37:24 +00:00
import 'package:cw_core/wallet_info.dart';
2021-01-15 17:41:30 +00:00
import 'package:cake_wallet/.secrets.g.dart' as secrets;
2022-02-02 12:40:40 +00:00
import 'package:cake_wallet/wallet_types.g.dart';
import 'package:cake_backup/backup.dart' as cake_backup;
2021-01-13 16:43:34 +00:00
class BackupService {
BackupService(
this._flutterSecureStorage, this._walletInfoSource, this._keyService, this._sharedPreferences)
2022-10-12 17:09:57 +00:00
: _cipher = Cryptography.instance.chacha20Poly1305Aead(),
_correctWallets = <WalletInfo>[];
2021-01-13 16:43:34 +00:00
static const currentVersion = _v2;
2021-01-15 17:41:30 +00:00
static const _v1 = 1;
static const _v2 = 2;
2021-01-15 17:41:30 +00:00
2021-01-13 16:43:34 +00:00
final Cipher _cipher;
final FlutterSecureStorage _flutterSecureStorage;
final SharedPreferences _sharedPreferences;
final Box<WalletInfo> _walletInfoSource;
final KeyService _keyService;
2022-02-02 12:40:40 +00:00
List<WalletInfo> _correctWallets;
2021-01-13 16:43:34 +00:00
Future<void> importBackup(Uint8List data, String password,
2021-01-15 17:41:30 +00:00
{String nonce = secrets.backupSalt}) async {
final version = getVersion(data);
switch (version) {
case _v1:
final backupBytes = data.toList()..removeAt(0);
final backupData = Uint8List.fromList(backupBytes);
2021-01-15 17:41:30 +00:00
await _importBackupV1(backupData, password, nonce: nonce);
break;
case _v2:
await _importBackupV2(data, password);
break;
2021-01-15 17:41:30 +00:00
default:
break;
}
}
Future<Uint8List> exportBackup(String password,
{String nonce = secrets.backupSalt, int version = currentVersion}) async {
switch (version) {
case _v1:
return await _exportBackupV1(password, nonce: nonce);
case _v2:
return await _exportBackupV2(password);
2021-01-15 17:41:30 +00:00
default:
2022-10-12 17:09:57 +00:00
throw Exception('Incorrect version: $version for exportBackup');
2021-01-15 17:41:30 +00:00
}
}
@Deprecated('Use v2 instead')
Future<Uint8List> _exportBackupV1(String password, {String nonce = secrets.backupSalt}) async =>
throw Exception('Deprecated. Export for backups v1 is deprecated. Please use export v2.');
Future<Uint8List> _exportBackupV2(String password) async {
2021-01-15 17:41:30 +00:00
final zipEncoder = ZipFileEncoder();
final appDir = await getApplicationDocumentsDirectory();
final now = DateTime.now();
final tmpDir = Directory('${appDir.path}/~_BACKUP_TMP');
final archivePath = '${tmpDir.path}/backup_${now.toString()}.zip';
final fileEntities = appDir.listSync(recursive: false);
final keychainDump = await _exportKeychainDumpV2(password);
2021-01-15 17:41:30 +00:00
final preferencesDump = await _exportPreferencesJSON();
final preferencesDumpFile = File('${tmpDir.path}/~_preferences_dump_TMP');
final keychainDumpFile = File('${tmpDir.path}/~_keychain_dump_TMP');
if (tmpDir.existsSync()) {
tmpDir.deleteSync(recursive: true);
}
tmpDir.createSync();
zipEncoder.create(archivePath);
fileEntities.forEach((entity) {
if (entity.path == archivePath || entity.path == tmpDir.path) {
return;
}
if (entity.statSync().type == FileSystemEntityType.directory) {
zipEncoder.addDirectory(Directory(entity.path));
} else {
zipEncoder.addFile(File(entity.path));
}
});
await keychainDumpFile.writeAsBytes(keychainDump.toList());
await preferencesDumpFile.writeAsString(preferencesDump);
2022-10-12 17:09:57 +00:00
await zipEncoder.addFile(preferencesDumpFile, '~_preferences_dump');
await zipEncoder.addFile(keychainDumpFile, '~_keychain_dump');
2021-01-15 17:41:30 +00:00
zipEncoder.close();
final content = File(archivePath).readAsBytesSync();
tmpDir.deleteSync(recursive: true);
return await _encryptV2(content, password);
2021-01-15 17:41:30 +00:00
}
Future<void> _importBackupV1(Uint8List data, String password, {required String nonce}) async {
2021-01-13 16:43:34 +00:00
final appDir = await getApplicationDocumentsDirectory();
final decryptedData = await _decryptV1(data, password, nonce);
2021-01-13 16:43:34 +00:00
final zip = ZipDecoder().decodeBytes(decryptedData);
zip.files.forEach((file) {
final filename = file.name;
if (file.isFile) {
2021-01-15 17:41:30 +00:00
final content = file.content as List<int>;
2021-01-13 16:43:34 +00:00
File('${appDir.path}/' + filename)
..createSync(recursive: true)
2021-01-15 17:41:30 +00:00
..writeAsBytesSync(content);
2021-01-13 16:43:34 +00:00
} else {
Directory('${appDir.path}/' + filename)..create(recursive: true);
}
});
2022-02-02 12:40:40 +00:00
await _verifyWallets();
await _importKeychainDumpV1(password, nonce: nonce);
await _importPreferencesDump();
}
Future<void> _importBackupV2(Uint8List data, String password) async {
final appDir = await getApplicationDocumentsDirectory();
final decryptedData = await _decryptV2(data, password);
final zip = ZipDecoder().decodeBytes(decryptedData);
zip.files.forEach((file) {
final filename = file.name;
if (file.isFile) {
final content = file.content as List<int>;
File('${appDir.path}/' + filename)
..createSync(recursive: true)
..writeAsBytesSync(content);
} else {
Directory('${appDir.path}/' + filename)..create(recursive: true);
}
});
await _verifyWallets();
await _importKeychainDumpV2(password);
2021-01-15 17:41:30 +00:00
await _importPreferencesDump();
2021-01-13 16:43:34 +00:00
}
2022-02-02 12:40:40 +00:00
Future<void> _verifyWallets() async {
final walletInfoSource = await _reloadHiveWalletInfoBox();
_correctWallets =
walletInfoSource.values.where((info) => availableWalletTypes.contains(info.type)).toList();
2022-02-02 12:40:40 +00:00
if (_correctWallets.isEmpty) {
throw Exception('Correct wallets not detected');
}
}
Future<Box<WalletInfo>> _reloadHiveWalletInfoBox() async {
final appDir = await getApplicationDocumentsDirectory();
await Hive.close();
Hive.init(appDir.path);
if (!Hive.isAdapterRegistered(WalletInfo.typeId)) {
Hive.registerAdapter(WalletInfoAdapter());
}
return await Hive.openBox<WalletInfo>(WalletInfo.boxName);
}
2021-01-15 17:41:30 +00:00
Future<void> _importPreferencesDump() async {
2021-01-13 16:43:34 +00:00
final appDir = await getApplicationDocumentsDirectory();
final preferencesFile = File('${appDir.path}/~_preferences_dump');
if (!preferencesFile.existsSync()) {
return;
}
final data = json.decode(preferencesFile.readAsStringSync()) as Map<String, dynamic>;
2022-02-02 12:40:40 +00:00
String currentWalletName = data[PreferencesKey.currentWalletName] as String;
int currentWalletType = data[PreferencesKey.currentWalletType] as int;
final isCorrentCurrentWallet = _correctWallets
.any((info) => info.name == currentWalletName && info.type.index == currentWalletType);
2022-02-02 12:40:40 +00:00
if (!isCorrentCurrentWallet) {
currentWalletName = _correctWallets.first.name;
2022-02-03 18:04:16 +00:00
currentWalletType = serializeToInt(_correctWallets.first.type);
2022-02-02 12:40:40 +00:00
}
2021-01-13 16:43:34 +00:00
2022-10-18 15:38:54 +00:00
final currentNodeId = data[PreferencesKey.currentNodeIdKey] as int?;
final currentBalanceDisplayMode = data[PreferencesKey.currentBalanceDisplayModeKey] as int?;
final currentFiatCurrency = data[PreferencesKey.currentFiatCurrencyKey] as String?;
final shouldSaveRecipientAddress = data[PreferencesKey.shouldSaveRecipientAddressKey] as bool?;
final isAppSecure = data[PreferencesKey.isAppSecureKey] as bool?;
final disableBuy = data[PreferencesKey.disableBuyKey] as bool?;
final disableSell = data[PreferencesKey.disableSellKey] as bool?;
final currentTransactionPriorityKeyLegacy =
data[PreferencesKey.currentTransactionPriorityKeyLegacy] as int?;
final allowBiometricalAuthentication =
data[PreferencesKey.allowBiometricalAuthenticationKey] as bool?;
final currentBitcoinElectrumSererId =
data[PreferencesKey.currentBitcoinElectrumSererIdKey] as int?;
2022-10-18 15:38:54 +00:00
final currentLanguageCode = data[PreferencesKey.currentLanguageCode] as String?;
final displayActionListMode = data[PreferencesKey.displayActionListModeKey] as int?;
final fiatApiMode = data[PreferencesKey.currentFiatApiModeKey] as int?;
2022-10-18 15:38:54 +00:00
final currentPinLength = data[PreferencesKey.currentPinLength] as int?;
final currentTheme = data[PreferencesKey.currentTheme] as int?;
2023-03-02 15:43:42 +00:00
final exchangeStatus = data[PreferencesKey.exchangeStatusKey] as int?;
final currentDefaultSettingsMigrationVersion =
data[PreferencesKey.currentDefaultSettingsMigrationVersion] as int?;
2022-10-18 15:38:54 +00:00
final moneroTransactionPriority = data[PreferencesKey.moneroTransactionPriority] as int?;
final bitcoinTransactionPriority = data[PreferencesKey.bitcoinTransactionPriority] as int?;
final selectedCake2FAPreset = data[PreferencesKey.selectedCake2FAPreset] as int?;
final shouldRequireTOTP2FAForAccessingWallet =
data[PreferencesKey.shouldRequireTOTP2FAForAccessingWallet] as bool?;
final shouldRequireTOTP2FAForSendsToContact =
data[PreferencesKey.shouldRequireTOTP2FAForSendsToContact] as bool?;
final shouldRequireTOTP2FAForSendsToNonContact =
data[PreferencesKey.shouldRequireTOTP2FAForSendsToNonContact] as bool?;
final shouldRequireTOTP2FAForSendsToInternalWallets =
data[PreferencesKey.shouldRequireTOTP2FAForSendsToInternalWallets] as bool?;
final shouldRequireTOTP2FAForExchangesToInternalWallets =
data[PreferencesKey.shouldRequireTOTP2FAForExchangesToInternalWallets] as bool?;
final shouldRequireTOTP2FAForAddingContacts =
data[PreferencesKey.shouldRequireTOTP2FAForAddingContacts] as bool?;
final shouldRequireTOTP2FAForCreatingNewWallets =
data[PreferencesKey.shouldRequireTOTP2FAForCreatingNewWallets] as bool?;
final shouldRequireTOTP2FAForAllSecurityAndBackupSettings =
data[PreferencesKey.shouldRequireTOTP2FAForAllSecurityAndBackupSettings] as bool?;
Cw 78 ethereum (#862) * Add initial flow for ethereum * Add initial create Eth wallet flow * Complete Ethereum wallet creation flow * Fix web3dart versioning issue * Add primary receive address extracted from private key * Implement open wallet functionality * Implement restore wallet from seed functionality * Fixate web3dart version as higher versions cause some issues * Add Initial Transaction priorities for eth Add estimated gas price * Rename priority value to tip * Re-order wallet types * Change ethereum node Fix connection issues * Fix estimating gas for priority * Add case for ethereum to fetch it's seeds * Add case for ethereum to request node * Fix Exchange screen initial pairs * Add initial send transaction flow * Add missing configure for ethereum class * Add Eth address initial setup * Fix Private key for Ethereum wallets * Change sign/send transaction flow * - Fix Conflicts with main - Remove unused function from Haven configure.dart * Add build command for ethereum package * Add missing Node list file to pubspec * - Fix balance display - Fix parsing of Ethereum amount - Add more Ethereum Nodes * - Fix extracting Ethereum Private key from seeds - Integrate signing/sending transaction with the send view model * - Update and Fix Conflicts with main * Add Balances for ERC20 tokens * Fix conflicts with main * Add erc20 abi json * Add send erc20 tokens initial function * add missing getHeightByDate in Haven * Allow contacts and wallets from the same tag * Add Shiba Inu icon * Add send ERC-20 tokens initial flow * Add missing import in generated file * Add initial approach for transaction sending for ERC-20 tokens * Refactor signing/sending transactions * Add initial flow for transactions subscription * Refactor signing/sending transactions * Add home settings icon * Fix conflicts with main * Initial flow for home settings * Add logic flow for adding erc20 tokens * Fix initial UI * Finalize UI for Tokens * Integrate UI with Ethereum flow * Add "Enable/Disable" feature for ERC20 tokens * Add initial Erc20 tokens * Add Sorting and Pin Native Token features * Fix price sorting * Sort tokens list as well when Sort criteria changes * - Improve sorting balances flow - Add initial add token from search bar flow * Fix Accounts Popup UI * Fix Pin native token * Fix Enabling/Disabling tokens Fix sorting by fiat once app is opened Improve token availability mechanism * Fix deleting token Fix renaming tokens * Fix issue with search * Add more tokens * - Fix scroll issue - Add ERC20 tokens placeholder image in picker * - Separate and organize default erc20 tokens - Fix scrolling - Add token placeholder images in picker - Sort disabled tokens alphabetically * Change BNB token initial availability * Fix Conflicts with main * Fix Conflicts with main * Add Verse ERC20 token to the initial tokens list * Add rename wallet to Ethereum * Integrate EtherScan API for fetching address transactions Generate Ethereum specific secrets in Ethereum package * Adjust transactions fiat price for ERC20 tokens * Free Up GitHub Actions Ubuntu Runner Disk Space * Free Up GitHub Actions Ubuntu Runner Disk space (trial 2) * Fix Transaction Fee display * Save transaction history * Enhance loading time for erc20 tokens transactions * Minor Fixes and Enhancements * Fix sending erc20 fix block explorer issue * Fix int overflow * Fix transaction amount conversions * Minor: `slow` -> `Slow` * Update build guide * Fix fetching fiat rate taking a lot of time by only fetching enabled tokens only and making the API calls in parallel not sequential * Update transactions on a periodic basis * For fee, use ETH spot price, not ERC-20 spot price * Add Etherscan History privacy option to enable/disable Etherscan API * Show estimated fee amounts in the send screen * fix send fiat fields parsing issue * Fix transactions estimated fee less than actual fee * handle balance sorting when balance is disabled Handle empty transactions list * Fix Delete Ethereum wallet Fix balance < 0.01 * Fix Decimal place for Ethereum amount Fix sending amount issue * Change words count * Remove balance hint and Full balance row from Ethereum wallets * support changing the asset type in send templates * Fix Templates for ERC tokens issues * Fix conflicts in send templates * Disable batch sending in Ethereum * Fix Fee calculation with different priorities * Fix Conflicts with main * Add offline error to ignored exceptions --------- Co-authored-by: Justin Ehrenhofer <justin.ehrenhofer@gmail.com>
2023-08-04 17:01:49 +00:00
final sortBalanceTokensBy = data[PreferencesKey.sortBalanceBy] as int?;
final pinNativeTokenAtTop = data[PreferencesKey.pinNativeTokenAtTop] as bool?;
final useEtherscan = data[PreferencesKey.useEtherscan] as bool?;
final syncAll = data[PreferencesKey.syncAllKey] as bool?;
final syncMode = data[PreferencesKey.syncModeKey] as int?;
await _sharedPreferences.setString(PreferencesKey.currentWalletName, currentWalletName);
2022-10-18 15:38:54 +00:00
if (currentNodeId != null)
await _sharedPreferences.setInt(PreferencesKey.currentNodeIdKey, currentNodeId);
2022-10-18 15:38:54 +00:00
if (currentBalanceDisplayMode != null)
await _sharedPreferences.setInt(
PreferencesKey.currentBalanceDisplayModeKey, currentBalanceDisplayMode);
2022-10-18 15:38:54 +00:00
await _sharedPreferences.setInt(PreferencesKey.currentWalletType, currentWalletType);
2022-10-18 15:38:54 +00:00
if (currentFiatCurrency != null)
await _sharedPreferences.setString(
PreferencesKey.currentFiatCurrencyKey, currentFiatCurrency);
2022-10-18 15:38:54 +00:00
if (shouldSaveRecipientAddress != null)
await _sharedPreferences.setBool(
PreferencesKey.shouldSaveRecipientAddressKey, shouldSaveRecipientAddress);
2022-10-18 15:38:54 +00:00
if (isAppSecure != null)
await _sharedPreferences.setBool(PreferencesKey.isAppSecureKey, isAppSecure);
if (disableBuy != null)
await _sharedPreferences.setBool(PreferencesKey.disableBuyKey, disableBuy);
if (disableSell != null)
await _sharedPreferences.setBool(PreferencesKey.disableSellKey, disableSell);
2022-10-18 15:38:54 +00:00
if (currentTransactionPriorityKeyLegacy != null)
await _sharedPreferences.setInt(
PreferencesKey.currentTransactionPriorityKeyLegacy, currentTransactionPriorityKeyLegacy);
2022-10-18 15:38:54 +00:00
if (allowBiometricalAuthentication != null)
await _sharedPreferences.setBool(
PreferencesKey.allowBiometricalAuthenticationKey, allowBiometricalAuthentication);
2022-10-18 15:38:54 +00:00
if (currentBitcoinElectrumSererId != null)
await _sharedPreferences.setInt(
PreferencesKey.currentBitcoinElectrumSererIdKey, currentBitcoinElectrumSererId);
2022-10-18 15:38:54 +00:00
if (currentLanguageCode != null)
await _sharedPreferences.setString(PreferencesKey.currentLanguageCode, currentLanguageCode);
2022-10-18 15:38:54 +00:00
if (displayActionListMode != null)
await _sharedPreferences.setInt(
PreferencesKey.displayActionListModeKey, displayActionListMode);
2022-10-18 15:38:54 +00:00
if (fiatApiMode != null)
await _sharedPreferences.setInt(PreferencesKey.currentFiatApiModeKey, fiatApiMode);
2022-10-18 15:38:54 +00:00
if (currentPinLength != null)
await _sharedPreferences.setInt(PreferencesKey.currentPinLength, currentPinLength);
2022-10-18 15:38:54 +00:00
if (currentTheme != null)
await _sharedPreferences.setInt(PreferencesKey.currentTheme, currentTheme);
2022-10-18 15:38:54 +00:00
2023-03-02 15:13:25 +00:00
if (exchangeStatus != null)
await _sharedPreferences.setInt(PreferencesKey.exchangeStatusKey, exchangeStatus);
2022-10-18 15:38:54 +00:00
if (currentDefaultSettingsMigrationVersion != null)
await _sharedPreferences.setInt(PreferencesKey.currentDefaultSettingsMigrationVersion,
currentDefaultSettingsMigrationVersion);
2022-10-18 15:38:54 +00:00
if (moneroTransactionPriority != null)
await _sharedPreferences.setInt(
PreferencesKey.moneroTransactionPriority, moneroTransactionPriority);
2022-10-18 15:38:54 +00:00
if (bitcoinTransactionPriority != null)
await _sharedPreferences.setInt(
PreferencesKey.bitcoinTransactionPriority, bitcoinTransactionPriority);
if (selectedCake2FAPreset != null)
await _sharedPreferences.setInt(PreferencesKey.selectedCake2FAPreset, selectedCake2FAPreset);
if (shouldRequireTOTP2FAForAccessingWallet != null)
await _sharedPreferences.setBool(PreferencesKey.shouldRequireTOTP2FAForAccessingWallet,
shouldRequireTOTP2FAForAccessingWallet);
if (shouldRequireTOTP2FAForSendsToContact != null)
await _sharedPreferences.setBool(PreferencesKey.shouldRequireTOTP2FAForSendsToContact,
shouldRequireTOTP2FAForSendsToContact);
if (shouldRequireTOTP2FAForSendsToNonContact != null)
await _sharedPreferences.setBool(PreferencesKey.shouldRequireTOTP2FAForSendsToNonContact,
shouldRequireTOTP2FAForSendsToNonContact);
if (shouldRequireTOTP2FAForSendsToInternalWallets != null)
await _sharedPreferences.setBool(PreferencesKey.shouldRequireTOTP2FAForSendsToInternalWallets,
shouldRequireTOTP2FAForSendsToInternalWallets);
if (shouldRequireTOTP2FAForExchangesToInternalWallets != null)
await _sharedPreferences.setBool(
PreferencesKey.shouldRequireTOTP2FAForExchangesToInternalWallets,
shouldRequireTOTP2FAForExchangesToInternalWallets);
if (shouldRequireTOTP2FAForAddingContacts != null)
await _sharedPreferences.setBool(PreferencesKey.shouldRequireTOTP2FAForAddingContacts,
shouldRequireTOTP2FAForAddingContacts);
if (shouldRequireTOTP2FAForCreatingNewWallets != null)
await _sharedPreferences.setBool(PreferencesKey.shouldRequireTOTP2FAForCreatingNewWallets,
shouldRequireTOTP2FAForCreatingNewWallets);
if (shouldRequireTOTP2FAForAllSecurityAndBackupSettings != null)
await _sharedPreferences.setBool(
PreferencesKey.shouldRequireTOTP2FAForAllSecurityAndBackupSettings,
shouldRequireTOTP2FAForAllSecurityAndBackupSettings);
2021-01-13 16:43:34 +00:00
Cw 78 ethereum (#862) * Add initial flow for ethereum * Add initial create Eth wallet flow * Complete Ethereum wallet creation flow * Fix web3dart versioning issue * Add primary receive address extracted from private key * Implement open wallet functionality * Implement restore wallet from seed functionality * Fixate web3dart version as higher versions cause some issues * Add Initial Transaction priorities for eth Add estimated gas price * Rename priority value to tip * Re-order wallet types * Change ethereum node Fix connection issues * Fix estimating gas for priority * Add case for ethereum to fetch it's seeds * Add case for ethereum to request node * Fix Exchange screen initial pairs * Add initial send transaction flow * Add missing configure for ethereum class * Add Eth address initial setup * Fix Private key for Ethereum wallets * Change sign/send transaction flow * - Fix Conflicts with main - Remove unused function from Haven configure.dart * Add build command for ethereum package * Add missing Node list file to pubspec * - Fix balance display - Fix parsing of Ethereum amount - Add more Ethereum Nodes * - Fix extracting Ethereum Private key from seeds - Integrate signing/sending transaction with the send view model * - Update and Fix Conflicts with main * Add Balances for ERC20 tokens * Fix conflicts with main * Add erc20 abi json * Add send erc20 tokens initial function * add missing getHeightByDate in Haven * Allow contacts and wallets from the same tag * Add Shiba Inu icon * Add send ERC-20 tokens initial flow * Add missing import in generated file * Add initial approach for transaction sending for ERC-20 tokens * Refactor signing/sending transactions * Add initial flow for transactions subscription * Refactor signing/sending transactions * Add home settings icon * Fix conflicts with main * Initial flow for home settings * Add logic flow for adding erc20 tokens * Fix initial UI * Finalize UI for Tokens * Integrate UI with Ethereum flow * Add "Enable/Disable" feature for ERC20 tokens * Add initial Erc20 tokens * Add Sorting and Pin Native Token features * Fix price sorting * Sort tokens list as well when Sort criteria changes * - Improve sorting balances flow - Add initial add token from search bar flow * Fix Accounts Popup UI * Fix Pin native token * Fix Enabling/Disabling tokens Fix sorting by fiat once app is opened Improve token availability mechanism * Fix deleting token Fix renaming tokens * Fix issue with search * Add more tokens * - Fix scroll issue - Add ERC20 tokens placeholder image in picker * - Separate and organize default erc20 tokens - Fix scrolling - Add token placeholder images in picker - Sort disabled tokens alphabetically * Change BNB token initial availability * Fix Conflicts with main * Fix Conflicts with main * Add Verse ERC20 token to the initial tokens list * Add rename wallet to Ethereum * Integrate EtherScan API for fetching address transactions Generate Ethereum specific secrets in Ethereum package * Adjust transactions fiat price for ERC20 tokens * Free Up GitHub Actions Ubuntu Runner Disk Space * Free Up GitHub Actions Ubuntu Runner Disk space (trial 2) * Fix Transaction Fee display * Save transaction history * Enhance loading time for erc20 tokens transactions * Minor Fixes and Enhancements * Fix sending erc20 fix block explorer issue * Fix int overflow * Fix transaction amount conversions * Minor: `slow` -> `Slow` * Update build guide * Fix fetching fiat rate taking a lot of time by only fetching enabled tokens only and making the API calls in parallel not sequential * Update transactions on a periodic basis * For fee, use ETH spot price, not ERC-20 spot price * Add Etherscan History privacy option to enable/disable Etherscan API * Show estimated fee amounts in the send screen * fix send fiat fields parsing issue * Fix transactions estimated fee less than actual fee * handle balance sorting when balance is disabled Handle empty transactions list * Fix Delete Ethereum wallet Fix balance < 0.01 * Fix Decimal place for Ethereum amount Fix sending amount issue * Change words count * Remove balance hint and Full balance row from Ethereum wallets * support changing the asset type in send templates * Fix Templates for ERC tokens issues * Fix conflicts in send templates * Disable batch sending in Ethereum * Fix Fee calculation with different priorities * Fix Conflicts with main * Add offline error to ignored exceptions --------- Co-authored-by: Justin Ehrenhofer <justin.ehrenhofer@gmail.com>
2023-08-04 17:01:49 +00:00
if (sortBalanceTokensBy != null)
await _sharedPreferences.setInt(PreferencesKey.sortBalanceBy, sortBalanceTokensBy);
if (pinNativeTokenAtTop != null)
await _sharedPreferences.setBool(PreferencesKey.pinNativeTokenAtTop, pinNativeTokenAtTop);
if (useEtherscan != null)
await _sharedPreferences.setBool(PreferencesKey.useEtherscan, useEtherscan);
if (syncAll != null)
await _sharedPreferences.setBool(PreferencesKey.syncAllKey, syncAll);
if (syncMode != null)
await _sharedPreferences.setInt(PreferencesKey.syncModeKey, syncMode);
2021-01-13 16:43:34 +00:00
await preferencesFile.delete();
}
Future<void> _importKeychainDumpV1(String password,
{required String nonce, String keychainSalt = secrets.backupKeychainSalt}) async {
2021-01-13 16:43:34 +00:00
final appDir = await getApplicationDocumentsDirectory();
final keychainDumpFile = File('${appDir.path}/~_keychain_dump');
final decryptedKeychainDumpFileData =
await _decryptV1(keychainDumpFile.readAsBytesSync(), '$keychainSalt$password', nonce);
final keychainJSON =
json.decode(utf8.decode(decryptedKeychainDumpFileData)) as Map<String, dynamic>;
2021-01-13 16:43:34 +00:00
final keychainWalletsInfo = keychainJSON['wallets'] as List;
final decodedPin = keychainJSON['pin'] as String;
final pinCodeKey = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final backupPasswordKey = generateStoreKeyFor(key: SecretStoreKey.backupPassword);
2021-01-15 17:41:30 +00:00
final backupPassword = keychainJSON[backupPasswordKey] as String;
await _flutterSecureStorage.write(key: backupPasswordKey, value: backupPassword);
2021-01-13 16:43:34 +00:00
keychainWalletsInfo.forEach((dynamic rawInfo) async {
final info = rawInfo as Map<String, dynamic>;
await importWalletKeychainInfo(info);
});
await _flutterSecureStorage.write(key: pinCodeKey, value: encodedPinCode(pin: decodedPin));
2021-01-13 16:43:34 +00:00
keychainDumpFile.deleteSync();
}
Future<void> _importKeychainDumpV2(String password,
{String keychainSalt = secrets.backupKeychainSalt}) async {
final appDir = await getApplicationDocumentsDirectory();
final keychainDumpFile = File('${appDir.path}/~_keychain_dump');
final decryptedKeychainDumpFileData =
await _decryptV2(keychainDumpFile.readAsBytesSync(), '$keychainSalt$password');
final keychainJSON =
json.decode(utf8.decode(decryptedKeychainDumpFileData)) as Map<String, dynamic>;
final keychainWalletsInfo = keychainJSON['wallets'] as List;
final decodedPin = keychainJSON['pin'] as String;
final pinCodeKey = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final backupPasswordKey = generateStoreKeyFor(key: SecretStoreKey.backupPassword);
final backupPassword = keychainJSON[backupPasswordKey] as String;
await _flutterSecureStorage.write(key: backupPasswordKey, value: backupPassword);
keychainWalletsInfo.forEach((dynamic rawInfo) async {
final info = rawInfo as Map<String, dynamic>;
await importWalletKeychainInfo(info);
});
await _flutterSecureStorage.write(key: pinCodeKey, value: encodedPinCode(pin: decodedPin));
keychainDumpFile.deleteSync();
}
2021-01-13 16:43:34 +00:00
Future<void> importWalletKeychainInfo(Map<String, dynamic> info) async {
final name = info['name'] as String;
final password = info['password'] as String;
await _keyService.saveWalletPassword(walletName: name, password: password);
}
@Deprecated('Use v2 instead')
Future<Uint8List> _exportKeychainDumpV1(String password,
{required String nonce, String keychainSalt = secrets.backupKeychainSalt}) async =>
throw Exception('Deprecated');
Future<Uint8List> _exportKeychainDumpV2(String password,
{String keychainSalt = secrets.backupKeychainSalt}) async {
2021-01-13 16:43:34 +00:00
final key = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final encodedPin = await _flutterSecureStorage.read(key: key);
2022-10-12 17:09:57 +00:00
final decodedPin = decodedPinCode(pin: encodedPin!);
final wallets = await Future.wait(_walletInfoSource.values.map((walletInfo) async {
2021-01-13 16:43:34 +00:00
return {
'name': walletInfo.name,
'type': walletInfo.type.toString(),
'password': await _keyService.getWalletPassword(walletName: walletInfo.name)
2021-01-13 16:43:34 +00:00
};
}));
final backupPasswordKey = generateStoreKeyFor(key: SecretStoreKey.backupPassword);
final backupPassword = await _flutterSecureStorage.read(key: backupPasswordKey);
final data = utf8.encode(
json.encode({'pin': decodedPin, 'wallets': wallets, backupPasswordKey: backupPassword}));
final encrypted = await _encryptV2(Uint8List.fromList(data), '$keychainSalt$password');
2021-01-13 16:43:34 +00:00
return encrypted;
}
2021-01-15 17:41:30 +00:00
Future<String> _exportPreferencesJSON() async {
2022-10-18 15:38:54 +00:00
final preferences = <String, dynamic>{
2021-01-13 16:43:34 +00:00
PreferencesKey.currentWalletName:
_sharedPreferences.getString(PreferencesKey.currentWalletName),
PreferencesKey.currentNodeIdKey: _sharedPreferences.getInt(PreferencesKey.currentNodeIdKey),
PreferencesKey.currentBalanceDisplayModeKey:
_sharedPreferences.getInt(PreferencesKey.currentBalanceDisplayModeKey),
PreferencesKey.currentWalletType: _sharedPreferences.getInt(PreferencesKey.currentWalletType),
2021-01-13 16:43:34 +00:00
PreferencesKey.currentFiatCurrencyKey:
_sharedPreferences.getString(PreferencesKey.currentFiatCurrencyKey),
PreferencesKey.shouldSaveRecipientAddressKey:
_sharedPreferences.getBool(PreferencesKey.shouldSaveRecipientAddressKey),
PreferencesKey.disableBuyKey: _sharedPreferences.getBool(PreferencesKey.disableBuyKey),
PreferencesKey.disableSellKey: _sharedPreferences.getBool(PreferencesKey.disableSellKey),
2021-01-13 17:18:28 +00:00
PreferencesKey.isDarkThemeLegacy:
_sharedPreferences.getBool(PreferencesKey.isDarkThemeLegacy),
PreferencesKey.currentPinLength: _sharedPreferences.getInt(PreferencesKey.currentPinLength),
PreferencesKey.currentTransactionPriorityKeyLegacy:
_sharedPreferences.getInt(PreferencesKey.currentTransactionPriorityKeyLegacy),
PreferencesKey.allowBiometricalAuthenticationKey:
_sharedPreferences.getBool(PreferencesKey.allowBiometricalAuthenticationKey),
PreferencesKey.currentBitcoinElectrumSererIdKey:
_sharedPreferences.getInt(PreferencesKey.currentBitcoinElectrumSererIdKey),
2021-01-13 16:43:34 +00:00
PreferencesKey.currentLanguageCode:
_sharedPreferences.getString(PreferencesKey.currentLanguageCode),
2021-01-13 16:43:34 +00:00
PreferencesKey.displayActionListModeKey:
_sharedPreferences.getInt(PreferencesKey.displayActionListModeKey),
PreferencesKey.currentTheme: _sharedPreferences.getInt(PreferencesKey.currentTheme),
PreferencesKey.exchangeStatusKey: _sharedPreferences.getInt(PreferencesKey.exchangeStatusKey),
PreferencesKey.currentDefaultSettingsMigrationVersion:
_sharedPreferences.getInt(PreferencesKey.currentDefaultSettingsMigrationVersion),
PreferencesKey.bitcoinTransactionPriority:
_sharedPreferences.getInt(PreferencesKey.bitcoinTransactionPriority),
PreferencesKey.moneroTransactionPriority:
_sharedPreferences.getInt(PreferencesKey.moneroTransactionPriority),
PreferencesKey.currentFiatApiModeKey:
_sharedPreferences.getInt(PreferencesKey.currentFiatApiModeKey),
PreferencesKey.selectedCake2FAPreset:
_sharedPreferences.getInt(PreferencesKey.selectedCake2FAPreset),
PreferencesKey.shouldRequireTOTP2FAForAccessingWallet:
_sharedPreferences.getBool(PreferencesKey.shouldRequireTOTP2FAForAccessingWallet),
PreferencesKey.shouldRequireTOTP2FAForSendsToContact:
_sharedPreferences.getBool(PreferencesKey.shouldRequireTOTP2FAForSendsToContact),
PreferencesKey.shouldRequireTOTP2FAForSendsToNonContact:
_sharedPreferences.getBool(PreferencesKey.shouldRequireTOTP2FAForSendsToNonContact),
PreferencesKey.shouldRequireTOTP2FAForSendsToInternalWallets:
_sharedPreferences.getBool(PreferencesKey.shouldRequireTOTP2FAForSendsToInternalWallets),
PreferencesKey.shouldRequireTOTP2FAForExchangesToInternalWallets: _sharedPreferences
.getBool(PreferencesKey.shouldRequireTOTP2FAForExchangesToInternalWallets),
PreferencesKey.shouldRequireTOTP2FAForAddingContacts:
_sharedPreferences.getBool(PreferencesKey.shouldRequireTOTP2FAForAddingContacts),
PreferencesKey.shouldRequireTOTP2FAForCreatingNewWallets:
_sharedPreferences.getBool(PreferencesKey.shouldRequireTOTP2FAForCreatingNewWallets),
PreferencesKey.shouldRequireTOTP2FAForAllSecurityAndBackupSettings: _sharedPreferences
.getBool(PreferencesKey.shouldRequireTOTP2FAForAllSecurityAndBackupSettings),
Cw 78 ethereum (#862) * Add initial flow for ethereum * Add initial create Eth wallet flow * Complete Ethereum wallet creation flow * Fix web3dart versioning issue * Add primary receive address extracted from private key * Implement open wallet functionality * Implement restore wallet from seed functionality * Fixate web3dart version as higher versions cause some issues * Add Initial Transaction priorities for eth Add estimated gas price * Rename priority value to tip * Re-order wallet types * Change ethereum node Fix connection issues * Fix estimating gas for priority * Add case for ethereum to fetch it's seeds * Add case for ethereum to request node * Fix Exchange screen initial pairs * Add initial send transaction flow * Add missing configure for ethereum class * Add Eth address initial setup * Fix Private key for Ethereum wallets * Change sign/send transaction flow * - Fix Conflicts with main - Remove unused function from Haven configure.dart * Add build command for ethereum package * Add missing Node list file to pubspec * - Fix balance display - Fix parsing of Ethereum amount - Add more Ethereum Nodes * - Fix extracting Ethereum Private key from seeds - Integrate signing/sending transaction with the send view model * - Update and Fix Conflicts with main * Add Balances for ERC20 tokens * Fix conflicts with main * Add erc20 abi json * Add send erc20 tokens initial function * add missing getHeightByDate in Haven * Allow contacts and wallets from the same tag * Add Shiba Inu icon * Add send ERC-20 tokens initial flow * Add missing import in generated file * Add initial approach for transaction sending for ERC-20 tokens * Refactor signing/sending transactions * Add initial flow for transactions subscription * Refactor signing/sending transactions * Add home settings icon * Fix conflicts with main * Initial flow for home settings * Add logic flow for adding erc20 tokens * Fix initial UI * Finalize UI for Tokens * Integrate UI with Ethereum flow * Add "Enable/Disable" feature for ERC20 tokens * Add initial Erc20 tokens * Add Sorting and Pin Native Token features * Fix price sorting * Sort tokens list as well when Sort criteria changes * - Improve sorting balances flow - Add initial add token from search bar flow * Fix Accounts Popup UI * Fix Pin native token * Fix Enabling/Disabling tokens Fix sorting by fiat once app is opened Improve token availability mechanism * Fix deleting token Fix renaming tokens * Fix issue with search * Add more tokens * - Fix scroll issue - Add ERC20 tokens placeholder image in picker * - Separate and organize default erc20 tokens - Fix scrolling - Add token placeholder images in picker - Sort disabled tokens alphabetically * Change BNB token initial availability * Fix Conflicts with main * Fix Conflicts with main * Add Verse ERC20 token to the initial tokens list * Add rename wallet to Ethereum * Integrate EtherScan API for fetching address transactions Generate Ethereum specific secrets in Ethereum package * Adjust transactions fiat price for ERC20 tokens * Free Up GitHub Actions Ubuntu Runner Disk Space * Free Up GitHub Actions Ubuntu Runner Disk space (trial 2) * Fix Transaction Fee display * Save transaction history * Enhance loading time for erc20 tokens transactions * Minor Fixes and Enhancements * Fix sending erc20 fix block explorer issue * Fix int overflow * Fix transaction amount conversions * Minor: `slow` -> `Slow` * Update build guide * Fix fetching fiat rate taking a lot of time by only fetching enabled tokens only and making the API calls in parallel not sequential * Update transactions on a periodic basis * For fee, use ETH spot price, not ERC-20 spot price * Add Etherscan History privacy option to enable/disable Etherscan API * Show estimated fee amounts in the send screen * fix send fiat fields parsing issue * Fix transactions estimated fee less than actual fee * handle balance sorting when balance is disabled Handle empty transactions list * Fix Delete Ethereum wallet Fix balance < 0.01 * Fix Decimal place for Ethereum amount Fix sending amount issue * Change words count * Remove balance hint and Full balance row from Ethereum wallets * support changing the asset type in send templates * Fix Templates for ERC tokens issues * Fix conflicts in send templates * Disable batch sending in Ethereum * Fix Fee calculation with different priorities * Fix Conflicts with main * Add offline error to ignored exceptions --------- Co-authored-by: Justin Ehrenhofer <justin.ehrenhofer@gmail.com>
2023-08-04 17:01:49 +00:00
PreferencesKey.sortBalanceBy:
_sharedPreferences.getInt(PreferencesKey.sortBalanceBy),
PreferencesKey.pinNativeTokenAtTop:
_sharedPreferences.getBool(PreferencesKey.pinNativeTokenAtTop),
PreferencesKey.useEtherscan:
_sharedPreferences.getBool(PreferencesKey.useEtherscan),
PreferencesKey.syncModeKey:
_sharedPreferences.getInt(PreferencesKey.syncModeKey),
PreferencesKey.syncAllKey:
_sharedPreferences.getBool(PreferencesKey.syncAllKey),
2021-01-13 16:43:34 +00:00
};
return json.encode(preferences);
}
2021-01-15 17:41:30 +00:00
int getVersion(Uint8List data) => data.toList().first;
Uint8List setVersion(Uint8List data, int version) {
final bytes = data.toList()..insert(0, version);
return Uint8List.fromList(bytes);
}
@Deprecated('Use v2 instead')
Future<Uint8List> _encryptV1(Uint8List data, String secretKeySource, String nonceBase64) async =>
throw Exception('Deprecated');
2021-01-13 16:43:34 +00:00
Future<Uint8List> _decryptV1(Uint8List data, String secretKeySource, String nonceBase64,
{int macLength = 16}) async {
2022-10-18 15:38:54 +00:00
final secretKeyHash = await Cryptography.instance.sha256().hash(utf8.encode(secretKeySource));
final secretKey = SecretKey(secretKeyHash.bytes);
final nonce = base64.decode(nonceBase64).toList();
final box = SecretBox(Uint8List.sublistView(data, 0, data.lengthInBytes - macLength).toList(),
nonce: nonce, mac: Mac(Uint8List.sublistView(data, data.lengthInBytes - macLength)));
2022-10-18 15:38:54 +00:00
final plainData = await _cipher.decrypt(box, secretKey: secretKey);
return Uint8List.fromList(plainData);
2021-01-13 16:43:34 +00:00
}
Future<Uint8List> _encryptV2(Uint8List data, String passphrase) async =>
cake_backup.encrypt(passphrase, data, version: _v2);
Future<Uint8List> _decryptV2(Uint8List data, String passphrase) async =>
cake_backup.decrypt(passphrase, data);
2021-01-13 16:43:34 +00:00
}