stack_wallet/lib/services/mixins/fusion_wallet_interface.dart

397 lines
13 KiB
Dart
Raw Normal View History

import 'dart:async';
2023-07-26 22:06:02 +00:00
import 'dart:io';
2023-10-09 21:42:42 +00:00
import 'dart:typed_data';
2023-07-26 22:06:02 +00:00
import 'package:bitbox/bitbox.dart' as bitbox;
2023-10-09 21:42:42 +00:00
import 'package:bitcoindart/bitcoindart.dart' as btcdart;
2023-09-28 16:41:39 +00:00
import 'package:fusiondart/fusiondart.dart' as fusion;
2023-07-26 22:06:02 +00:00
import 'package:isar/isar.dart';
import 'package:stackwallet/db/isar/main_db.dart';
2023-09-19 22:58:55 +00:00
import 'package:stackwallet/electrumx_rpc/cached_electrumx.dart';
import 'package:stackwallet/models/fusion_progress_ui_state.dart';
2023-08-07 18:54:44 +00:00
import 'package:stackwallet/models/isar/models/isar_models.dart';
2023-10-12 22:05:17 +00:00
import 'package:stackwallet/pages_desktop_specific/cashfusion/sub_widgets/fusion_dialog.dart';
2023-09-22 21:44:40 +00:00
import 'package:stackwallet/services/fusion_tor_service.dart';
2023-10-09 21:42:42 +00:00
import 'package:stackwallet/utilities/bip32_utils.dart';
2023-07-26 22:06:02 +00:00
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/utilities/stack_file_system.dart';
2023-07-26 22:06:02 +00:00
2023-08-07 18:54:44 +00:00
const String kReservedFusionAddress = "reserved_fusion_address";
/// A mixin for the BitcoinCashWallet class that adds CashFusion functionality.
mixin FusionWalletInterface {
// Passed in wallet data.
2023-09-22 16:48:14 +00:00
late final String _walletId;
2023-07-26 22:06:02 +00:00
late final Coin _coin;
2023-09-22 16:48:14 +00:00
late final MainDB _db;
2023-09-22 21:44:40 +00:00
late final FusionTorService _torService;
2023-10-09 21:42:42 +00:00
late final Future<String?> _mnemonic;
late final Future<String?> _mnemonicPassphrase;
late final btcdart.NetworkType _network;
2023-07-26 22:06:02 +00:00
// setting values on this should notify any listeners (the GUI)
FusionProgressUIState? _uiState;
FusionProgressUIState get uiState {
if (_uiState == null) {
throw Exception("FusionProgressUIState has not been set for $_walletId");
}
return _uiState!;
}
set uiState(FusionProgressUIState state) {
if (_uiState != null) {
throw Exception("FusionProgressUIState was already set for $_walletId");
}
_uiState = state;
}
// Passed in wallet functions.
2023-10-13 18:17:59 +00:00
late final Future<List<Address>> Function({int numberOfAddresses})
_getNextUnusedChangeAddresses;
late final CachedElectrumX Function() _getWalletCachedElectrumX;
late final Future<int> Function({
required String address,
}) _getTxCountForAddress;
2023-09-28 16:05:06 +00:00
late final Future<int> Function() _getChainHeight;
/// Initializes the FusionWalletInterface mixin.
///
/// This function must be called before any other functions in this mixin.
Future<void> initFusionInterface({
2023-07-26 22:06:02 +00:00
required String walletId,
required Coin coin,
required MainDB db,
2023-10-13 18:17:59 +00:00
required Future<List<Address>> Function({int numberOfAddresses})
getNextUnusedChangeAddress,
required CachedElectrumX Function() getWalletCachedElectrumX,
required Future<int> Function({
required String address,
}) getTxCountForAddress,
2023-09-28 16:05:06 +00:00
required Future<int> Function() getChainHeight,
2023-10-09 21:42:42 +00:00
required Future<String?> mnemonic,
required Future<String?> mnemonicPassphrase,
required btcdart.NetworkType network,
}) async {
// Set passed in wallet data.
2023-07-26 22:06:02 +00:00
_walletId = walletId;
_coin = coin;
_db = db;
2023-10-13 18:17:59 +00:00
_getNextUnusedChangeAddresses = getNextUnusedChangeAddress;
2023-09-22 21:44:40 +00:00
_torService = FusionTorService.sharedInstance;
_getWalletCachedElectrumX = getWalletCachedElectrumX;
_getTxCountForAddress = getTxCountForAddress;
2023-09-28 16:05:06 +00:00
_getChainHeight = getChainHeight;
2023-10-09 21:42:42 +00:00
_mnemonic = mnemonic;
_mnemonicPassphrase = mnemonicPassphrase;
_network = network;
2023-07-26 22:06:02 +00:00
}
// callback to update the ui state object
void _updateStatus(fusion.FusionStatus fusionStatus) {
2023-10-12 22:05:17 +00:00
switch (fusionStatus) {
case fusion.FusionStatus.connecting:
_uiState?.connecting = CashFusionStatus.running;
2023-10-12 22:05:17 +00:00
break;
case fusion.FusionStatus.setup:
_uiState?.connecting = CashFusionStatus.success;
_uiState?.outputs = CashFusionStatus.running;
2023-10-12 22:05:17 +00:00
break;
case fusion.FusionStatus.waiting:
_uiState?.outputs = CashFusionStatus.success;
_uiState?.peers = CashFusionStatus.running;
2023-10-12 22:05:17 +00:00
break;
case fusion.FusionStatus.running:
_uiState?.peers = CashFusionStatus.success;
_uiState?.fusing = CashFusionStatus.running;
2023-10-12 22:05:17 +00:00
break;
case fusion.FusionStatus.complete:
2023-10-13 17:41:01 +00:00
_uiState?.fusing = CashFusionStatus.success;
_uiState?.complete = CashFusionStatus.success;
2023-10-12 22:05:17 +00:00
break;
case fusion.FusionStatus.failed:
2023-10-13 17:41:01 +00:00
_uiState?.fusing = CashFusionStatus.failed;
_uiState?.complete = CashFusionStatus.failed;
failCurrentUiState();
2023-10-12 22:05:17 +00:00
break;
case fusion.FusionStatus.exception:
2023-10-13 17:41:01 +00:00
_uiState?.complete = CashFusionStatus.failed;
failCurrentUiState();
2023-10-12 22:05:17 +00:00
break;
case fusion.FusionStatus.reset:
_uiState?.outputs = CashFusionStatus.waiting;
_uiState?.peers = CashFusionStatus.waiting;
_uiState?.connecting = CashFusionStatus.waiting;
_uiState?.fusing = CashFusionStatus.waiting;
_uiState?.complete = CashFusionStatus.waiting;
_uiState?.fusionState = CashFusionStatus.waiting;
break;
2023-10-12 22:05:17 +00:00
}
}
void failCurrentUiState() {
// Check each _uiState value to see if it is running. If so, set it to failed.
if (_uiState?.connecting == CashFusionStatus.running) {
_uiState?.connecting = CashFusionStatus.failed;
}
if (_uiState?.outputs == CashFusionStatus.running) {
_uiState?.outputs = CashFusionStatus.failed;
}
if (_uiState?.peers == CashFusionStatus.running) {
_uiState?.peers = CashFusionStatus.failed;
}
if (_uiState?.fusing == CashFusionStatus.running) {
_uiState?.fusing = CashFusionStatus.failed;
}
}
/// Returns a list of all transactions in the wallet for the given address.
Future<List<Map<String, dynamic>>> _getTransactionsByAddress(
String address,
) async {
final txidList =
await _db.getTransactions(_walletId).txidProperty().findAll();
final futures = txidList.map(
(e) => _getWalletCachedElectrumX().getTransaction(
txHash: e,
coin: _coin,
),
);
2023-09-19 22:58:55 +00:00
return await Future.wait(futures);
}
Future<Uint8List> _getPrivateKeyForPubKey(List<int> pubKey) async {
2023-10-09 21:42:42 +00:00
// can't directly query for equal lists in isar so we need to fetch
// all addresses then search in dart
try {
final derivationPath = (await _db
.getAddresses(_walletId)
.filter()
.typeEqualTo(AddressType.p2pkh)
.and()
.derivationPathIsNotNull()
.and()
.group((q) => q
.subTypeEqualTo(AddressSubType.receiving)
.or()
.subTypeEqualTo(AddressSubType.change))
.findAll())
2023-10-09 21:42:42 +00:00
.firstWhere((e) => e.publicKey.toString() == pubKey.toString())
.derivationPath!
.value;
final node = await Bip32Utils.getBip32Node(
(await _mnemonic)!,
(await _mnemonicPassphrase)!,
_network,
derivationPath,
);
return node.privateKey!;
} catch (_) {
throw Exception("Derivation path for pubkey=$pubKey could not be found");
}
}
2023-10-13 18:17:59 +00:00
/// Reserve an address for fusion.
Future<Address> _reserveAddress(Address address) async {
address = address.copyWith(otherData: kReservedFusionAddress);
2023-08-07 18:54:44 +00:00
2023-10-13 18:17:59 +00:00
// Make sure the address is updated in the database as reserved for Fusion.
final _address = await _db.getAddress(_walletId, address.value);
if (_address != null) {
await _db.updateAddress(_address, address);
} else {
await _db.putAddress(address);
}
2023-08-07 18:54:44 +00:00
return address;
}
2023-10-13 18:17:59 +00:00
/// un reserve a fusion reserved address.
/// If [address] is not reserved nothing happens
Future<Address> _unReserveAddress(Address address) async {
if (address.otherData != kReservedFusionAddress) {
return address;
}
final updated = address.copyWith(otherData: null);
// Make sure the address is updated in the database.
await _db.updateAddress(address, updated);
return updated;
}
/// Returns a list of unused reserved change addresses.
///
/// If there are not enough unused reserved change addresses, new ones are created.
Future<List<fusion.Address>> _getUnusedReservedChangeAddresses(
2023-08-07 18:54:44 +00:00
int numberOfAddresses,
) async {
2023-10-13 18:17:59 +00:00
final unusedChangeAddresses = await _getNextUnusedChangeAddresses(
numberOfAddresses: numberOfAddresses,
);
2023-08-07 18:54:44 +00:00
// Initialize a list of unused reserved change addresses.
2023-10-13 18:17:59 +00:00
final List<Address> unusedReservedAddresses = [];
for (final address in unusedChangeAddresses) {
unusedReservedAddresses.add(await _reserveAddress(address));
2023-08-07 18:54:44 +00:00
}
// Return the list of unused reserved change addresses.
2023-10-13 18:17:59 +00:00
return unusedReservedAddresses
.map(
(e) => fusion.Address(
address: e.value,
publicKey: e.publicKey,
fusionReserved: true,
derivationPath: fusion.DerivationPath(
e.derivationPath!.value,
),
),
)
.toList();
}
2023-09-22 21:44:40 +00:00
int _torStartCount = 0;
/// Returns the current Tor proxy address.
Future<({InternetAddress host, int port})> _getSocksProxyAddress() async {
2023-09-22 21:44:40 +00:00
if (_torStartCount > 5) {
// something is quite broken so stop trying to recursively fetch
// start up tor and fetch proxy info
throw Exception(
"Fusion interface attempted to start tor $_torStartCount times and failed!",
);
}
2023-09-22 21:44:40 +00:00
try {
final info = _torService.getProxyInfo();
2023-09-22 21:44:40 +00:00
// reset counter before return info;
_torStartCount = 0;
return info;
} catch (_) {
// tor is probably not running so lets fix that
final torDir = await StackFileSystem.applicationTorDirectory();
_torService.init(torDataDirPath: torDir.path);
// increment start attempt count
_torStartCount++;
await _torService.start();
// try again to fetch proxy info
return await _getSocksProxyAddress();
2023-09-22 21:44:40 +00:00
}
}
// Initial attempt for CashFusion integration goes here.
/// Fuse the wallet's UTXOs.
///
/// This function is called when the user taps the "Fuse" button in the UI.
Future<void> fuse() async {
2023-07-26 22:06:02 +00:00
// Initial attempt for CashFusion integration goes here.
2023-09-28 16:41:39 +00:00
final mainFusionObject = fusion.Fusion(fusion.FusionParams());
2023-07-26 22:06:02 +00:00
// Pass wallet functions to the Fusion object
2023-09-27 20:04:24 +00:00
await mainFusionObject.initFusion(
getTransactionsByAddress: _getTransactionsByAddress,
getUnusedReservedChangeAddresses: _getUnusedReservedChangeAddresses,
getSocksProxyAddress: _getSocksProxyAddress,
getChainHeight: _getChainHeight,
updateStatusCallback: _updateStatus,
getTransactionJson: (String txid) async =>
await _getWalletCachedElectrumX().getTransaction(
coin: _coin,
txHash: txid,
),
getPrivateKeyForPubKey: _getPrivateKeyForPubKey,
broadcastTransaction: (String txHex) => _getWalletCachedElectrumX()
.electrumXClient
.broadcastTransaction(rawTx: txHex),
);
2023-10-12 18:03:57 +00:00
// Add unfrozen stack UTXOs.
final List<UTXO> walletUtxos = await _db
.getUTXOs(_walletId)
.filter()
.isBlockedEqualTo(false)
.and()
.addressIsNotNull()
.findAll();
2023-09-28 17:44:17 +00:00
final List<fusion.UtxoDTO> coinList = [];
2023-09-19 22:58:55 +00:00
// Loop through UTXOs, checking and adding valid ones.
for (final utxo in walletUtxos) {
final String addressString = utxo.address!;
final List<String> possibleAddresses = [addressString];
if (bitbox.Address.detectFormat(addressString) ==
bitbox.Address.formatCashAddr) {
possibleAddresses.add(bitbox.Address.toLegacyAddress(addressString));
} else {
possibleAddresses.add(bitbox.Address.toCashAddress(addressString));
2023-09-19 22:58:55 +00:00
}
// Fetch address to get pubkey
final addr = await _db
.getAddresses(_walletId)
.filter()
.anyOf<String, QueryBuilder<Address, Address, QAfterFilterCondition>>(
possibleAddresses, (q, e) => q.valueEqualTo(e))
.and()
.group((q) => q
.subTypeEqualTo(AddressSubType.change)
.or()
.subTypeEqualTo(AddressSubType.receiving))
.and()
.typeEqualTo(AddressType.p2pkh)
.findFirst();
2023-10-12 18:03:57 +00:00
// depending on the address type in the query above this can be null
if (addr == null) {
// A utxo object should always have a non null address.
// If non found then just ignore the UTXO (aka don't fuse it)
Logging.instance.log(
"Ignoring utxo=$utxo for address=\"$addressString\" while selecting UTXOs for Fusion",
level: LogLevel.Info,
);
continue;
}
2023-10-12 18:03:57 +00:00
final dto = fusion.UtxoDTO(
txid: utxo.txid,
vout: utxo.vout,
value: utxo.value,
address: utxo.address!,
pubKey: addr.publicKey,
2023-09-22 20:25:38 +00:00
);
2023-09-19 22:58:55 +00:00
// Add UTXO to coinList.
2023-10-12 18:03:57 +00:00
coinList.add(dto);
2023-09-19 22:58:55 +00:00
}
// Fuse UTXOs.
2023-10-09 16:06:27 +00:00
return await mainFusionObject.fuse(
2023-10-12 18:03:57 +00:00
inputsFromWallet: coinList,
2023-10-09 16:06:27 +00:00
network:
_coin.isTestNet ? fusion.Utilities.testNet : fusion.Utilities.mainNet,
);
2023-07-26 22:06:02 +00:00
}
Future<void> refreshFusion() {
// TODO
throw UnimplementedError(
"TODO refreshFusion eg look up number of fusion participants connected/coordinating");
2023-07-26 22:06:02 +00:00
}
}