2021-12-24 12:52:08 +00:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:convert';
|
2022-01-12 13:20:43 +00:00
|
|
|
import 'dart:math';
|
2022-01-17 15:33:51 +00:00
|
|
|
import 'dart:typed_data';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:cw_core/unspent_coins_info.dart';
|
|
|
|
import 'package:hive/hive.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum_wallet_addresses.dart';
|
|
|
|
import 'package:mobx/mobx.dart';
|
|
|
|
import 'package:rxdart/subjects.dart';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
|
|
|
|
import 'package:cw_bitcoin/electrum_transaction_info.dart';
|
|
|
|
import 'package:cw_core/pathForWallet.dart';
|
|
|
|
import 'package:cw_bitcoin/address_to_output_script.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_address_record.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum_balance.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_mnemonic.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_transaction_credentials.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum_transaction_history.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_transaction_no_inputs_exception.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_transaction_priority.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_transaction_wrong_balance_exception.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_unspent.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_wallet_keys.dart';
|
|
|
|
import 'package:cw_bitcoin/file.dart';
|
|
|
|
import 'package:cw_bitcoin/pending_bitcoin_transaction.dart';
|
|
|
|
import 'package:cw_bitcoin/script_hash.dart';
|
|
|
|
import 'package:cw_bitcoin/utils.dart';
|
|
|
|
import 'package:cw_core/wallet_base.dart';
|
|
|
|
import 'package:cw_core/node.dart';
|
|
|
|
import 'package:cw_core/sync_status.dart';
|
|
|
|
import 'package:cw_core/transaction_priority.dart';
|
|
|
|
import 'package:cw_core/wallet_info.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum.dart';
|
2022-01-17 15:33:51 +00:00
|
|
|
import 'package:hex/hex.dart';
|
2022-03-30 15:57:04 +00:00
|
|
|
import 'package:cw_core/crypto_currency.dart';
|
2022-10-12 17:09:57 +00:00
|
|
|
import 'package:collection/collection.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
part 'electrum_wallet.g.dart';
|
|
|
|
|
|
|
|
class ElectrumWallet = ElectrumWalletBase with _$ElectrumWallet;
|
|
|
|
|
|
|
|
abstract class ElectrumWalletBase extends WalletBase<ElectrumBalance,
|
|
|
|
ElectrumTransactionHistory, ElectrumTransactionInfo> with Store {
|
|
|
|
ElectrumWalletBase(
|
2022-10-12 17:09:57 +00:00
|
|
|
{required String password,
|
|
|
|
required WalletInfo walletInfo,
|
|
|
|
required Box<UnspentCoinsInfo> unspentCoinsInfo,
|
|
|
|
required this.networkType,
|
|
|
|
required this.mnemonic,
|
|
|
|
required Uint8List seedBytes,
|
|
|
|
List<BitcoinAddressRecord>? initialAddresses,
|
|
|
|
ElectrumClient? electrumClient,
|
|
|
|
ElectrumBalance? initialBalance,
|
|
|
|
CryptoCurrency? currency})
|
|
|
|
: hd = bitcoin.HDWallet.fromSeed(seedBytes, network: networkType)
|
2021-12-24 12:52:08 +00:00
|
|
|
.derivePath("m/0'/0"),
|
|
|
|
syncStatus = NotConnectedSyncStatus(),
|
|
|
|
_password = password,
|
|
|
|
_feeRates = <int>[],
|
|
|
|
_isTransactionUpdating = false,
|
2022-10-12 17:09:57 +00:00
|
|
|
unspentCoins = [],
|
|
|
|
_scripthashesUpdateSubject = {},
|
|
|
|
balance = ObservableMap<CryptoCurrency, ElectrumBalance>.of(
|
|
|
|
currency != null
|
|
|
|
? {currency: initialBalance ?? const ElectrumBalance(confirmed: 0, unconfirmed: 0)}
|
|
|
|
: {}),
|
|
|
|
this.unspentCoinsInfo = unspentCoinsInfo,
|
2021-12-24 12:52:08 +00:00
|
|
|
super(walletInfo) {
|
|
|
|
this.electrumClient = electrumClient ?? ElectrumClient();
|
|
|
|
this.walletInfo = walletInfo;
|
|
|
|
transactionHistory =
|
|
|
|
ElectrumTransactionHistory(walletInfo: walletInfo, password: password);
|
|
|
|
}
|
|
|
|
|
|
|
|
static int estimatedTransactionSize(int inputsCount, int outputsCounts) =>
|
|
|
|
inputsCount * 146 + outputsCounts * 33 + 8;
|
|
|
|
|
|
|
|
final bitcoin.HDWallet hd;
|
|
|
|
final String mnemonic;
|
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
late ElectrumClient electrumClient;
|
2021-12-24 12:52:08 +00:00
|
|
|
Box<UnspentCoinsInfo> unspentCoinsInfo;
|
|
|
|
|
|
|
|
@override
|
2022-10-12 17:09:57 +00:00
|
|
|
late ElectrumWalletAddresses walletAddresses;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
@observable
|
2022-10-12 17:09:57 +00:00
|
|
|
late ObservableMap<CryptoCurrency, ElectrumBalance> balance;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
@observable
|
|
|
|
SyncStatus syncStatus;
|
|
|
|
|
|
|
|
List<String> get scriptHashes => walletAddresses.addresses
|
|
|
|
.map((addr) => scriptHash(addr.address, networkType: networkType))
|
|
|
|
.toList();
|
|
|
|
|
|
|
|
List<String> get publicScriptHashes => walletAddresses.addresses
|
|
|
|
.where((addr) => !addr.isHidden)
|
|
|
|
.map((addr) => scriptHash(addr.address, networkType: networkType))
|
|
|
|
.toList();
|
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
String get xpub => hd.base58!;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
String get seed => mnemonic;
|
|
|
|
|
|
|
|
bitcoin.NetworkType networkType;
|
|
|
|
|
|
|
|
@override
|
|
|
|
BitcoinWalletKeys get keys => BitcoinWalletKeys(
|
2022-10-12 17:09:57 +00:00
|
|
|
wif: hd.wif!, privateKey: hd.privKey!, publicKey: hd.pubKey!);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2022-07-19 14:29:28 +00:00
|
|
|
String _password;
|
2021-12-24 12:52:08 +00:00
|
|
|
List<BitcoinUnspent> unspentCoins;
|
|
|
|
List<int> _feeRates;
|
2022-10-12 17:09:57 +00:00
|
|
|
Map<String, BehaviorSubject<Object>?> _scripthashesUpdateSubject;
|
2021-12-24 12:52:08 +00:00
|
|
|
bool _isTransactionUpdating;
|
|
|
|
|
|
|
|
Future<void> init() async {
|
|
|
|
await walletAddresses.init();
|
|
|
|
await transactionHistory.init();
|
|
|
|
await save();
|
|
|
|
}
|
|
|
|
|
|
|
|
@action
|
|
|
|
@override
|
|
|
|
Future<void> startSync() async {
|
|
|
|
try {
|
2022-11-09 10:14:21 +00:00
|
|
|
syncStatus = AttemptingSyncStatus();
|
2022-01-18 16:27:33 +00:00
|
|
|
await walletAddresses.discoverAddresses();
|
2021-12-24 12:52:08 +00:00
|
|
|
await updateTransactions();
|
|
|
|
_subscribeForUpdates();
|
|
|
|
await _updateBalance();
|
|
|
|
await updateUnspent();
|
|
|
|
_feeRates = await electrumClient.feeRates();
|
|
|
|
|
|
|
|
Timer.periodic(const Duration(minutes: 1),
|
|
|
|
(timer) async => _feeRates = await electrumClient.feeRates());
|
|
|
|
|
|
|
|
syncStatus = SyncedSyncStatus();
|
2022-10-12 17:09:57 +00:00
|
|
|
} catch (e, stacktrace) {
|
|
|
|
print(stacktrace);
|
2021-12-24 12:52:08 +00:00
|
|
|
print(e.toString());
|
|
|
|
syncStatus = FailedSyncStatus();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@action
|
|
|
|
@override
|
2022-10-12 17:09:57 +00:00
|
|
|
Future<void> connectToNode({required Node node}) async {
|
2021-12-24 12:52:08 +00:00
|
|
|
try {
|
|
|
|
syncStatus = ConnectingSyncStatus();
|
|
|
|
await electrumClient.connectToUri(node.uri);
|
|
|
|
electrumClient.onConnectionStatusChange = (bool isConnected) {
|
|
|
|
if (!isConnected) {
|
|
|
|
syncStatus = LostConnectionSyncStatus();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
syncStatus = ConnectedSyncStatus();
|
|
|
|
} catch (e) {
|
|
|
|
print(e.toString());
|
|
|
|
syncStatus = FailedSyncStatus();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<PendingBitcoinTransaction> createTransaction(
|
|
|
|
Object credentials) async {
|
|
|
|
const minAmount = 546;
|
|
|
|
final transactionCredentials = credentials as BitcoinTransactionCredentials;
|
|
|
|
final inputs = <BitcoinUnspent>[];
|
|
|
|
final outputs = transactionCredentials.outputs;
|
|
|
|
final hasMultiDestination = outputs.length > 1;
|
|
|
|
var allInputsAmount = 0;
|
|
|
|
|
|
|
|
if (unspentCoins.isEmpty) {
|
|
|
|
await updateUnspent();
|
|
|
|
}
|
|
|
|
|
|
|
|
for (final utx in unspentCoins) {
|
|
|
|
if (utx.isSending) {
|
|
|
|
allInputsAmount += utx.value;
|
|
|
|
inputs.add(utx);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (inputs.isEmpty) {
|
|
|
|
throw BitcoinTransactionNoInputsException();
|
|
|
|
}
|
|
|
|
|
2022-12-16 17:21:40 +00:00
|
|
|
final allAmountFee = transactionCredentials.feeRate != null
|
|
|
|
? feeAmountWithFeeRate(transactionCredentials.feeRate!, inputs.length, outputs.length)
|
|
|
|
: feeAmountForPriority(transactionCredentials.priority!, inputs.length, outputs.length);
|
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
final allAmount = allInputsAmount - allAmountFee;
|
|
|
|
|
|
|
|
var credentialsAmount = 0;
|
|
|
|
var amount = 0;
|
|
|
|
var fee = 0;
|
|
|
|
|
|
|
|
if (hasMultiDestination) {
|
|
|
|
if (outputs.any((item) => item.sendAll
|
2022-10-12 17:09:57 +00:00
|
|
|
|| item.formattedCryptoAmount! <= 0)) {
|
2021-12-24 12:52:08 +00:00
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
|
|
|
|
|
|
|
credentialsAmount = outputs.fold(0, (acc, value) =>
|
2022-10-12 17:09:57 +00:00
|
|
|
acc + value.formattedCryptoAmount!);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
if (allAmount - credentialsAmount < minAmount) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
|
|
|
|
|
|
|
amount = credentialsAmount;
|
2022-07-28 17:03:16 +00:00
|
|
|
|
|
|
|
if (transactionCredentials.feeRate != null) {
|
2022-10-12 17:09:57 +00:00
|
|
|
fee = calculateEstimatedFeeWithFeeRate(transactionCredentials.feeRate!, amount,
|
2022-07-28 17:03:16 +00:00
|
|
|
outputsCount: outputs.length + 1);
|
|
|
|
} else {
|
|
|
|
fee = calculateEstimatedFee(transactionCredentials.priority, amount,
|
|
|
|
outputsCount: outputs.length + 1);
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
} else {
|
|
|
|
final output = outputs.first;
|
|
|
|
credentialsAmount = !output.sendAll
|
2022-10-12 17:09:57 +00:00
|
|
|
? output.formattedCryptoAmount!
|
2021-12-24 12:52:08 +00:00
|
|
|
: 0;
|
|
|
|
|
|
|
|
if (credentialsAmount > allAmount) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
|
|
|
|
|
|
|
amount = output.sendAll || allAmount - credentialsAmount < minAmount
|
|
|
|
? allAmount
|
|
|
|
: credentialsAmount;
|
2022-07-28 17:03:16 +00:00
|
|
|
|
|
|
|
if (output.sendAll || amount == allAmount) {
|
|
|
|
fee = allAmountFee;
|
|
|
|
} else if (transactionCredentials.feeRate != null) {
|
2022-10-12 17:09:57 +00:00
|
|
|
fee = calculateEstimatedFeeWithFeeRate(transactionCredentials.feeRate!, amount);
|
2022-07-28 17:03:16 +00:00
|
|
|
} else {
|
|
|
|
fee = calculateEstimatedFee(transactionCredentials.priority, amount);
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (fee == 0) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
|
|
|
|
|
|
|
final totalAmount = amount + fee;
|
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
if (totalAmount > balance[currency]!.confirmed || totalAmount > allInputsAmount) {
|
2021-12-24 12:52:08 +00:00
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
|
|
|
|
|
|
|
final txb = bitcoin.TransactionBuilder(network: networkType);
|
2022-01-18 16:27:33 +00:00
|
|
|
final changeAddress = await walletAddresses.getChangeAddress();
|
2021-12-24 12:52:08 +00:00
|
|
|
var leftAmount = totalAmount;
|
|
|
|
var totalInputAmount = 0;
|
|
|
|
|
|
|
|
inputs.clear();
|
|
|
|
|
|
|
|
for (final utx in unspentCoins) {
|
|
|
|
if (utx.isSending) {
|
|
|
|
leftAmount = leftAmount - utx.value;
|
|
|
|
totalInputAmount += utx.value;
|
|
|
|
inputs.add(utx);
|
|
|
|
|
|
|
|
if (leftAmount <= 0) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (inputs.isEmpty) {
|
|
|
|
throw BitcoinTransactionNoInputsException();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (amount <= 0 || totalInputAmount < totalAmount) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
|
|
|
|
|
|
|
txb.setVersion(1);
|
|
|
|
inputs.forEach((input) {
|
|
|
|
if (input.isP2wpkh) {
|
|
|
|
final p2wpkh = bitcoin
|
|
|
|
.P2WPKH(
|
2022-01-14 13:07:41 +00:00
|
|
|
data: generatePaymentData(
|
|
|
|
hd: input.address.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd,
|
|
|
|
index: input.address.index),
|
2021-12-24 12:52:08 +00:00
|
|
|
network: networkType)
|
|
|
|
.data;
|
|
|
|
|
|
|
|
txb.addInput(input.hash, input.vout, null, p2wpkh.output);
|
|
|
|
} else {
|
|
|
|
txb.addInput(input.hash, input.vout);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
outputs.forEach((item) {
|
|
|
|
final outputAmount = hasMultiDestination
|
|
|
|
? item.formattedCryptoAmount
|
|
|
|
: amount;
|
|
|
|
final outputAddress = item.isParsedAddress
|
2022-10-12 17:09:57 +00:00
|
|
|
? item.extractedAddress!
|
2021-12-24 12:52:08 +00:00
|
|
|
: item.address;
|
|
|
|
txb.addOutput(
|
|
|
|
addressToOutputScript(outputAddress, networkType),
|
2022-10-12 17:09:57 +00:00
|
|
|
outputAmount!);
|
2021-12-24 12:52:08 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
final estimatedSize =
|
|
|
|
estimatedTransactionSize(inputs.length, outputs.length + 1);
|
2022-07-28 17:03:16 +00:00
|
|
|
var feeAmount = 0;
|
|
|
|
|
|
|
|
if (transactionCredentials.feeRate != null) {
|
2022-10-12 17:09:57 +00:00
|
|
|
feeAmount = transactionCredentials.feeRate! * estimatedSize;
|
2022-07-28 17:03:16 +00:00
|
|
|
} else {
|
2022-10-12 17:09:57 +00:00
|
|
|
feeAmount = feeRate(transactionCredentials.priority!) * estimatedSize;
|
2022-07-28 17:03:16 +00:00
|
|
|
}
|
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
final changeValue = totalInputAmount - amount - feeAmount;
|
|
|
|
|
|
|
|
if (changeValue > minAmount) {
|
|
|
|
txb.addOutput(changeAddress, changeValue);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (var i = 0; i < inputs.length; i++) {
|
|
|
|
final input = inputs[i];
|
|
|
|
final keyPair = generateKeyPair(
|
2022-01-14 11:15:20 +00:00
|
|
|
hd: input.address.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd,
|
|
|
|
index: input.address.index,
|
|
|
|
network: networkType);
|
2021-12-24 12:52:08 +00:00
|
|
|
final witnessValue = input.isP2wpkh ? input.value : null;
|
|
|
|
|
|
|
|
txb.sign(vin: i, keyPair: keyPair, witnessValue: witnessValue);
|
|
|
|
}
|
|
|
|
|
|
|
|
return PendingBitcoinTransaction(txb.build(), type,
|
|
|
|
electrumClient: electrumClient, amount: amount, fee: fee)
|
|
|
|
..addListener((transaction) async {
|
|
|
|
transactionHistory.addOne(transaction);
|
|
|
|
await _updateBalance();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
String toJSON() => json.encode({
|
|
|
|
'mnemonic': mnemonic,
|
2022-01-18 16:27:33 +00:00
|
|
|
'account_index': walletAddresses.currentReceiveAddressIndex.toString(),
|
|
|
|
'change_address_index': walletAddresses.currentChangeAddressIndex.toString(),
|
2021-12-24 12:52:08 +00:00
|
|
|
'addresses': walletAddresses.addresses.map((addr) => addr.toJSON()).toList(),
|
2022-03-30 15:57:04 +00:00
|
|
|
'balance': balance[currency]?.toJSON()
|
2021-12-24 12:52:08 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
int feeRate(TransactionPriority priority) {
|
2022-01-13 14:48:42 +00:00
|
|
|
try {
|
|
|
|
if (priority is BitcoinTransactionPriority) {
|
|
|
|
return _feeRates[priority.raw];
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2022-01-13 14:48:42 +00:00
|
|
|
return 0;
|
|
|
|
} catch(_) {
|
|
|
|
return 0;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int feeAmountForPriority(BitcoinTransactionPriority priority, int inputsCount,
|
|
|
|
int outputsCount) =>
|
|
|
|
feeRate(priority) * estimatedTransactionSize(inputsCount, outputsCount);
|
|
|
|
|
2022-07-28 17:03:16 +00:00
|
|
|
int feeAmountWithFeeRate(int feeRate, int inputsCount,
|
|
|
|
int outputsCount) =>
|
|
|
|
feeRate * estimatedTransactionSize(inputsCount, outputsCount);
|
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
@override
|
2022-10-12 17:09:57 +00:00
|
|
|
int calculateEstimatedFee(TransactionPriority? priority, int? amount,
|
|
|
|
{int? outputsCount}) {
|
2021-12-24 12:52:08 +00:00
|
|
|
if (priority is BitcoinTransactionPriority) {
|
2022-07-28 17:03:16 +00:00
|
|
|
return calculateEstimatedFeeWithFeeRate(
|
|
|
|
feeRate(priority),
|
|
|
|
amount,
|
|
|
|
outputsCount: outputsCount);
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2022-07-28 17:03:16 +00:00
|
|
|
return 0;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
int calculateEstimatedFeeWithFeeRate(int feeRate, int? amount,
|
|
|
|
{int? outputsCount}) {
|
2022-07-28 17:03:16 +00:00
|
|
|
int inputsCount = 0;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2022-07-28 17:03:16 +00:00
|
|
|
if (amount != null) {
|
|
|
|
int totalValue = 0;
|
|
|
|
|
|
|
|
for (final input in unspentCoins) {
|
|
|
|
if (totalValue >= amount) {
|
|
|
|
break;
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
2022-07-28 17:03:16 +00:00
|
|
|
if (input.isSending) {
|
|
|
|
totalValue += input.value;
|
|
|
|
inputsCount += 1;
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-28 17:03:16 +00:00
|
|
|
if (totalValue < amount) return 0;
|
|
|
|
} else {
|
|
|
|
for (final input in unspentCoins) {
|
|
|
|
if (input.isSending) {
|
|
|
|
inputsCount += 1;
|
|
|
|
}
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
2022-07-28 17:03:16 +00:00
|
|
|
// If send all, then we have no change value
|
|
|
|
final _outputsCount = outputsCount ?? (amount != null ? 2 : 1);
|
|
|
|
|
|
|
|
return feeAmountWithFeeRate(
|
|
|
|
feeRate, inputsCount, _outputsCount);
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> save() async {
|
|
|
|
final path = await makePath();
|
|
|
|
await write(path: path, password: _password, data: toJSON());
|
|
|
|
await transactionHistory.save();
|
|
|
|
}
|
|
|
|
|
2022-07-19 14:29:28 +00:00
|
|
|
@override
|
|
|
|
Future<void> changePassword(String password) async {
|
|
|
|
_password = password;
|
|
|
|
await save();
|
|
|
|
await transactionHistory.changePassword(password);
|
|
|
|
}
|
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
bitcoin.ECPair keyPairFor({required int index}) =>
|
2021-12-24 12:52:08 +00:00
|
|
|
generateKeyPair(hd: hd, index: index, network: networkType);
|
|
|
|
|
|
|
|
@override
|
2022-10-12 17:09:57 +00:00
|
|
|
Future<void> rescan({required int height}) async => throw UnimplementedError();
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> close() async {
|
|
|
|
try {
|
2022-10-12 17:09:57 +00:00
|
|
|
await electrumClient.close();
|
2021-12-24 12:52:08 +00:00
|
|
|
} catch (_) {}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<String> makePath() async =>
|
|
|
|
pathForWallet(name: walletInfo.name, type: walletInfo.type);
|
|
|
|
|
|
|
|
Future<void> updateUnspent() async {
|
|
|
|
final unspent = await Future.wait(walletAddresses
|
|
|
|
.addresses.map((address) => electrumClient
|
|
|
|
.getListUnspentWithAddress(address.address, networkType)
|
|
|
|
.then((unspent) => unspent
|
2022-10-17 20:55:41 +00:00
|
|
|
.map((unspent) {
|
|
|
|
try {
|
|
|
|
return BitcoinUnspent.fromJSON(address, unspent);
|
|
|
|
} catch(_) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}).whereNotNull())));
|
2021-12-24 12:52:08 +00:00
|
|
|
unspentCoins = unspent.expand((e) => e).toList();
|
|
|
|
|
|
|
|
if (unspentCoinsInfo.isEmpty) {
|
|
|
|
unspentCoins.forEach((coin) => _addCoinInfo(coin));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (unspentCoins.isNotEmpty) {
|
|
|
|
unspentCoins.forEach((coin) {
|
|
|
|
final coinInfoList = unspentCoinsInfo.values.where((element) =>
|
|
|
|
element.walletId.contains(id) && element.hash.contains(coin.hash));
|
|
|
|
|
|
|
|
if (coinInfoList.isNotEmpty) {
|
|
|
|
final coinInfo = coinInfoList.first;
|
|
|
|
|
|
|
|
coin.isFrozen = coinInfo.isFrozen;
|
|
|
|
coin.isSending = coinInfo.isSending;
|
|
|
|
coin.note = coinInfo.note;
|
|
|
|
} else {
|
|
|
|
_addCoinInfo(coin);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
await _refreshUnspentCoinsInfo();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _addCoinInfo(BitcoinUnspent coin) async {
|
|
|
|
final newInfo = UnspentCoinsInfo(
|
|
|
|
walletId: id,
|
|
|
|
hash: coin.hash,
|
|
|
|
isFrozen: coin.isFrozen,
|
|
|
|
isSending: coin.isSending,
|
2022-11-01 21:43:39 +00:00
|
|
|
noteRaw: coin.note
|
2021-12-24 12:52:08 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
await unspentCoinsInfo.add(newInfo);
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _refreshUnspentCoinsInfo() async {
|
|
|
|
try {
|
|
|
|
final List<dynamic> keys = <dynamic>[];
|
|
|
|
final currentWalletUnspentCoins = unspentCoinsInfo.values
|
|
|
|
.where((element) => element.walletId.contains(id));
|
|
|
|
|
|
|
|
if (currentWalletUnspentCoins.isNotEmpty) {
|
|
|
|
currentWalletUnspentCoins.forEach((element) {
|
2022-10-12 17:09:57 +00:00
|
|
|
final existUnspentCoins = unspentCoins.where((coin) => element.hash.contains(coin.hash));
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2022-10-12 17:09:57 +00:00
|
|
|
if (existUnspentCoins.isEmpty) {
|
2021-12-24 12:52:08 +00:00
|
|
|
keys.add(element.key);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (keys.isNotEmpty) {
|
|
|
|
await unspentCoinsInfo.deleteAll(keys);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
print(e.toString());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-17 15:33:51 +00:00
|
|
|
Future<ElectrumTransactionBundle> getTransactionExpanded(
|
2022-10-12 17:09:57 +00:00
|
|
|
{required String hash, required int height}) async {
|
2022-01-17 15:33:51 +00:00
|
|
|
final verboseTransaction = await electrumClient.getTransactionRaw(hash: hash);
|
|
|
|
final transactionHex = verboseTransaction['hex'] as String;
|
|
|
|
final original = bitcoin.Transaction.fromHex(transactionHex);
|
|
|
|
final ins = <bitcoin.Transaction>[];
|
|
|
|
final time = verboseTransaction['time'] as int;
|
2022-01-24 12:04:23 +00:00
|
|
|
final confirmations = verboseTransaction['confirmations'] as int ?? 0;
|
2022-01-17 15:33:51 +00:00
|
|
|
|
|
|
|
for (final vin in original.ins) {
|
2022-10-12 17:09:57 +00:00
|
|
|
final id = HEX.encode(vin.hash!.reversed.toList());
|
2022-01-17 15:33:51 +00:00
|
|
|
final txHex = await electrumClient.getTransactionHex(hash: id);
|
|
|
|
final tx = bitcoin.Transaction.fromHex(txHex);
|
|
|
|
ins.add(tx);
|
|
|
|
}
|
|
|
|
|
|
|
|
return ElectrumTransactionBundle(
|
|
|
|
original,
|
|
|
|
ins: ins,
|
|
|
|
time: time,
|
|
|
|
confirmations: confirmations);
|
|
|
|
}
|
|
|
|
|
2022-10-17 20:55:41 +00:00
|
|
|
Future<ElectrumTransactionInfo?> fetchTransactionInfo(
|
2022-10-12 17:09:57 +00:00
|
|
|
{required String hash, required int height}) async {
|
2022-10-17 20:55:41 +00:00
|
|
|
try {
|
2022-01-17 15:33:51 +00:00
|
|
|
final tx = await getTransactionExpanded(hash: hash, height: height);
|
|
|
|
final addresses = walletAddresses.addresses.map((addr) => addr.address).toSet();
|
|
|
|
return ElectrumTransactionInfo.fromElectrumBundle(
|
2022-01-27 09:20:51 +00:00
|
|
|
tx,
|
|
|
|
walletInfo.type,
|
|
|
|
networkType,
|
|
|
|
addresses: addresses,
|
|
|
|
height: height);
|
2022-10-17 20:55:41 +00:00
|
|
|
} catch(_) {
|
|
|
|
return null;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<Map<String, ElectrumTransactionInfo>> fetchTransactions() async {
|
2022-01-24 12:04:23 +00:00
|
|
|
final addressHashes = <String, BitcoinAddressRecord>{};
|
|
|
|
final normalizedHistories = <Map<String, dynamic>>[];
|
|
|
|
walletAddresses.addresses.forEach((addressRecord) {
|
|
|
|
final sh = scriptHash(addressRecord.address, networkType: networkType);
|
|
|
|
addressHashes[sh] = addressRecord;
|
|
|
|
});
|
2021-12-24 12:52:08 +00:00
|
|
|
final histories =
|
2022-01-24 12:04:23 +00:00
|
|
|
addressHashes.keys.map((scriptHash) => electrumClient
|
|
|
|
.getHistory(scriptHash)
|
|
|
|
.then((history) => {scriptHash: history}));
|
|
|
|
final historyResults = await Future.wait(histories);
|
|
|
|
historyResults.forEach((history) {
|
|
|
|
history.entries.forEach((historyItem) {
|
|
|
|
if (historyItem.value.isNotEmpty) {
|
|
|
|
final address = addressHashes[historyItem.key];
|
2022-10-12 17:09:57 +00:00
|
|
|
address?.setAsUsed();
|
2022-01-24 12:04:23 +00:00
|
|
|
normalizedHistories.addAll(historyItem.value);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
final historiesWithDetails = await Future.wait(
|
|
|
|
normalizedHistories
|
2022-10-17 20:55:41 +00:00
|
|
|
.map((transaction) {
|
|
|
|
try {
|
|
|
|
return fetchTransactionInfo(
|
|
|
|
hash: transaction['tx_hash'] as String,
|
|
|
|
height: transaction['height'] as int);
|
|
|
|
} catch(_) {
|
|
|
|
return Future.value(null);
|
|
|
|
}
|
|
|
|
}));
|
2021-12-24 12:52:08 +00:00
|
|
|
return historiesWithDetails.fold<Map<String, ElectrumTransactionInfo>>(
|
|
|
|
<String, ElectrumTransactionInfo>{}, (acc, tx) {
|
2022-10-17 20:55:41 +00:00
|
|
|
if (tx == null) {
|
|
|
|
return acc;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
acc[tx.id] = acc[tx.id]?.updated(tx) ?? tx;
|
|
|
|
return acc;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> updateTransactions() async {
|
|
|
|
try {
|
|
|
|
if (_isTransactionUpdating) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
_isTransactionUpdating = true;
|
|
|
|
final transactions = await fetchTransactions();
|
|
|
|
transactionHistory.addMany(transactions);
|
2022-01-24 12:04:23 +00:00
|
|
|
walletAddresses.updateReceiveAddresses();
|
2021-12-24 12:52:08 +00:00
|
|
|
await transactionHistory.save();
|
|
|
|
_isTransactionUpdating = false;
|
2022-10-17 20:55:41 +00:00
|
|
|
} catch (e, stacktrace) {
|
|
|
|
print(stacktrace);
|
2021-12-24 12:52:08 +00:00
|
|
|
print(e);
|
|
|
|
_isTransactionUpdating = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void _subscribeForUpdates() {
|
|
|
|
scriptHashes.forEach((sh) async {
|
|
|
|
await _scripthashesUpdateSubject[sh]?.close();
|
|
|
|
_scripthashesUpdateSubject[sh] = electrumClient.scripthashUpdate(sh);
|
2022-01-17 15:33:51 +00:00
|
|
|
_scripthashesUpdateSubject[sh]?.listen((event) async {
|
2021-12-24 12:52:08 +00:00
|
|
|
try {
|
|
|
|
await _updateBalance();
|
|
|
|
await updateUnspent();
|
|
|
|
await updateTransactions();
|
|
|
|
} catch (e) {
|
|
|
|
print(e.toString());
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<ElectrumBalance> _fetchBalances() async {
|
2022-01-18 16:27:33 +00:00
|
|
|
final addresses = walletAddresses.addresses.toList();
|
|
|
|
final balanceFutures = <Future<Map<String, dynamic>>>[];
|
|
|
|
|
|
|
|
for (var i = 0; i < addresses.length; i++) {
|
|
|
|
final addressRecord = addresses[i];
|
|
|
|
final sh = scriptHash(addressRecord.address, networkType: networkType);
|
|
|
|
final balanceFuture = electrumClient.getBalance(sh);
|
|
|
|
balanceFutures.add(balanceFuture);
|
|
|
|
}
|
|
|
|
|
|
|
|
final balances = await Future.wait(balanceFutures);
|
|
|
|
var totalConfirmed = 0;
|
|
|
|
var totalUnconfirmed = 0;
|
|
|
|
|
|
|
|
for (var i = 0; i < balances.length; i++) {
|
|
|
|
final addressRecord = addresses[i];
|
|
|
|
final balance = balances[i];
|
2022-10-12 17:09:57 +00:00
|
|
|
final confirmed = balance['confirmed'] as int? ?? 0;
|
|
|
|
final unconfirmed = balance['unconfirmed'] as int? ?? 0;
|
2022-01-18 16:27:33 +00:00
|
|
|
totalConfirmed += confirmed;
|
|
|
|
totalUnconfirmed += unconfirmed;
|
|
|
|
|
|
|
|
if (confirmed > 0 || unconfirmed > 0) {
|
|
|
|
addressRecord.setAsUsed();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ElectrumBalance(confirmed: totalConfirmed, unconfirmed: totalUnconfirmed);
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _updateBalance() async {
|
2022-03-30 15:57:04 +00:00
|
|
|
balance[currency] = await _fetchBalances();
|
2021-12-24 12:52:08 +00:00
|
|
|
await save();
|
|
|
|
}
|
2022-01-12 13:20:43 +00:00
|
|
|
|
|
|
|
String getChangeAddress() {
|
|
|
|
const minCountOfHiddenAddresses = 5;
|
|
|
|
final random = Random();
|
|
|
|
var addresses = walletAddresses.addresses
|
|
|
|
.where((addr) => addr.isHidden)
|
|
|
|
.toList();
|
|
|
|
|
|
|
|
if (addresses.length < minCountOfHiddenAddresses) {
|
|
|
|
addresses = walletAddresses.addresses.toList();
|
|
|
|
}
|
|
|
|
|
|
|
|
return addresses[random.nextInt(addresses.length)].address;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|