2021-12-24 12:52:08 +00:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:convert';
|
2023-07-12 23:20:11 +00:00
|
|
|
import 'dart:io';
|
2022-01-12 13:20:43 +00:00
|
|
|
import 'dart:math';
|
2023-11-15 23:12:23 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
import 'package:bitcoin_base/bitcoin_base.dart';
|
2023-10-06 00:38:39 +00:00
|
|
|
import 'package:cw_core/encryption_file_utils.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
|
2024-03-04 19:42:57 +00:00
|
|
|
import 'package:bitcoin_base/bitcoin_base.dart' as bitcoin_base;
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:collection/collection.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:cw_bitcoin/bitcoin_address_record.dart';
|
|
|
|
import 'package:cw_bitcoin/bitcoin_transaction_credentials.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';
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:cw_bitcoin/electrum.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum_balance.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum_transaction_history.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum_transaction_info.dart';
|
|
|
|
import 'package:cw_bitcoin/electrum_wallet_addresses.dart';
|
2024-03-04 19:42:57 +00:00
|
|
|
import 'package:cw_bitcoin/litecoin_network.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:cw_bitcoin/pending_bitcoin_transaction.dart';
|
|
|
|
import 'package:cw_bitcoin/script_hash.dart';
|
|
|
|
import 'package:cw_bitcoin/utils.dart';
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:cw_core/crypto_currency.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:cw_core/node.dart';
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:cw_core/pathForWallet.dart';
|
|
|
|
import 'package:cw_core/pending_transaction.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:cw_core/sync_status.dart';
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:cw_core/transaction_direction.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:cw_core/transaction_priority.dart';
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:cw_core/unspent_coins_info.dart';
|
2023-12-02 01:02:55 +00:00
|
|
|
import 'package:cw_core/utils/file.dart';
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:cw_core/wallet_base.dart';
|
2021-12-24 12:52:08 +00:00
|
|
|
import 'package:cw_core/wallet_info.dart';
|
2023-11-15 23:12:23 +00:00
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import 'package:hive/hive.dart';
|
|
|
|
import 'package:mobx/mobx.dart';
|
|
|
|
import 'package:rxdart/subjects.dart';
|
2024-03-04 19:42:57 +00:00
|
|
|
import 'package:http/http.dart' as http;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
part 'electrum_wallet.g.dart';
|
|
|
|
|
|
|
|
class ElectrumWallet = ElectrumWalletBase with _$ElectrumWallet;
|
|
|
|
|
2023-10-12 22:50:16 +00:00
|
|
|
abstract class ElectrumWalletBase
|
|
|
|
extends WalletBase<ElectrumBalance, ElectrumTransactionHistory, ElectrumTransactionInfo>
|
|
|
|
with Store {
|
2021-12-24 12:52:08 +00:00
|
|
|
ElectrumWalletBase(
|
2022-10-12 17:09:57 +00:00
|
|
|
{required String password,
|
2023-10-12 22:50:16 +00:00
|
|
|
required WalletInfo walletInfo,
|
|
|
|
required Box<UnspentCoinsInfo> unspentCoinsInfo,
|
|
|
|
required this.networkType,
|
|
|
|
required this.mnemonic,
|
|
|
|
required Uint8List seedBytes,
|
2023-10-13 14:29:46 +00:00
|
|
|
required this.encryptionFileUtils,
|
2023-10-12 22:50:16 +00:00
|
|
|
List<BitcoinAddressRecord>? initialAddresses,
|
|
|
|
ElectrumClient? electrumClient,
|
|
|
|
ElectrumBalance? initialBalance,
|
|
|
|
CryptoCurrency? currency})
|
|
|
|
: hd = currency == CryptoCurrency.bch
|
2023-11-15 23:12:23 +00:00
|
|
|
? bitcoinCashHDWallet(seedBytes)
|
|
|
|
: bitcoin.HDWallet.fromSeed(seedBytes, network: networkType).derivePath("m/0'/0"),
|
2021-12-24 12:52:08 +00:00
|
|
|
syncStatus = NotConnectedSyncStatus(),
|
|
|
|
_password = password,
|
|
|
|
_feeRates = <int>[],
|
|
|
|
_isTransactionUpdating = false,
|
2024-01-23 05:15:24 +00:00
|
|
|
isEnabledAutoGenerateSubaddress = true,
|
2022-10-12 17:09:57 +00:00
|
|
|
unspentCoins = [],
|
|
|
|
_scripthashesUpdateSubject = {},
|
2023-10-12 22:50:16 +00:00
|
|
|
balance = ObservableMap<CryptoCurrency, ElectrumBalance>.of(currency != null
|
|
|
|
? {
|
2023-11-15 23:12:23 +00:00
|
|
|
currency:
|
|
|
|
initialBalance ?? const ElectrumBalance(confirmed: 0, unconfirmed: 0, frozen: 0)
|
|
|
|
}
|
2023-10-12 22:50:16 +00:00
|
|
|
: {}),
|
2022-10-12 17:09:57 +00:00
|
|
|
this.unspentCoinsInfo = unspentCoinsInfo,
|
2024-03-04 19:42:57 +00:00
|
|
|
this.network = networkType == bitcoin.bitcoin
|
|
|
|
? BitcoinNetwork.mainnet
|
|
|
|
: networkType == litecoinNetwork
|
|
|
|
? LitecoinNetwork.mainnet
|
|
|
|
: BitcoinNetwork.testnet,
|
|
|
|
this.isTestnet = networkType == bitcoin.testnet,
|
2021-12-24 12:52:08 +00:00
|
|
|
super(walletInfo) {
|
|
|
|
this.electrumClient = electrumClient ?? ElectrumClient();
|
|
|
|
this.walletInfo = walletInfo;
|
|
|
|
transactionHistory =
|
2023-04-10 23:16:13 +00:00
|
|
|
ElectrumTransactionHistory(
|
|
|
|
walletInfo: walletInfo,
|
|
|
|
password: password,
|
|
|
|
encryptionFileUtils: encryptionFileUtils);
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
2023-10-12 22:50:16 +00:00
|
|
|
static bitcoin.HDWallet bitcoinCashHDWallet(Uint8List seedBytes) =>
|
2023-11-15 23:12:23 +00:00
|
|
|
bitcoin.HDWallet.fromSeed(seedBytes).derivePath("m/44'/145'/0'/0");
|
2023-10-12 22:50:16 +00:00
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
static int estimatedTransactionSize(int inputsCount, int outputsCounts) =>
|
2023-12-13 14:43:26 +00:00
|
|
|
inputsCount * 68 + outputsCounts * 34 + 10;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
final bitcoin.HDWallet hd;
|
|
|
|
final String mnemonic;
|
2023-04-10 23:16:13 +00:00
|
|
|
final EncryptionFileUtils encryptionFileUtils;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-01-23 05:15:24 +00:00
|
|
|
@override
|
|
|
|
@observable
|
|
|
|
bool isEnabledAutoGenerateSubaddress;
|
|
|
|
|
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;
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
List<String> get scriptHashes => walletAddresses.addressesByReceiveType
|
|
|
|
.map((addr) => scriptHash(addr.address, network: network))
|
2021-12-24 12:52:08 +00:00
|
|
|
.toList();
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
List<String> get publicScriptHashes => walletAddresses.allAddresses
|
2023-10-12 22:50:16 +00:00
|
|
|
.where((addr) => !addr.isHidden)
|
2024-03-04 19:42:57 +00:00
|
|
|
.map((addr) => scriptHash(addr.address, network: network))
|
2023-10-12 22:50:16 +00:00
|
|
|
.toList();
|
2021-12-24 12:52:08 +00:00
|
|
|
|
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;
|
|
|
|
|
2023-03-30 22:33:59 +00:00
|
|
|
@override
|
|
|
|
String get password => _password;
|
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
bitcoin.NetworkType networkType;
|
2024-03-04 19:42:57 +00:00
|
|
|
BasedUtxoNetwork network;
|
|
|
|
|
|
|
|
@override
|
|
|
|
bool? isTestnet;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
@override
|
2023-10-12 22:50:16 +00:00
|
|
|
BitcoinWalletKeys get keys =>
|
|
|
|
BitcoinWalletKeys(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;
|
|
|
|
|
2023-06-16 01:14:01 +00:00
|
|
|
void Function(FlutterErrorDetails)? _onError;
|
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
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();
|
2021-12-24 12:52:08 +00:00
|
|
|
await updateTransactions();
|
|
|
|
_subscribeForUpdates();
|
|
|
|
await updateUnspent();
|
2023-04-20 13:46:41 +00:00
|
|
|
await updateBalance();
|
2024-03-04 19:42:57 +00:00
|
|
|
_feeRates = await electrumClient.feeRates(network: network);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2023-10-12 22:50:16 +00:00
|
|
|
Timer.periodic(
|
|
|
|
const Duration(minutes: 1), (timer) async => _feeRates = await electrumClient.feeRates());
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
Future<EstimatedTxResult> _estimateTxFeeAndInputsToUse(
|
|
|
|
int credentialsAmount,
|
|
|
|
bool sendAll,
|
|
|
|
List<BitcoinBaseAddress> outputAddresses,
|
|
|
|
List<BitcoinOutput> outputs,
|
|
|
|
BitcoinTransactionCredentials transactionCredentials,
|
|
|
|
{int? inputsCount}) async {
|
|
|
|
final utxos = <UtxoWithAddress>[];
|
|
|
|
List<ECPrivate> privateKeys = [];
|
|
|
|
|
|
|
|
var leftAmount = credentialsAmount;
|
2021-12-24 12:52:08 +00:00
|
|
|
var allInputsAmount = 0;
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
for (int i = 0; i < unspentCoins.length; i++) {
|
|
|
|
final utx = unspentCoins[i];
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
if (utx.isSending) {
|
|
|
|
allInputsAmount += utx.value;
|
2024-03-04 19:42:57 +00:00
|
|
|
leftAmount = leftAmount - utx.value;
|
|
|
|
|
|
|
|
final address = _addressTypeFromStr(utx.address, network);
|
|
|
|
final privkey = generateECPrivate(
|
|
|
|
hd: utx.bitcoinAddressRecord.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd,
|
|
|
|
index: utx.bitcoinAddressRecord.index,
|
|
|
|
network: network);
|
|
|
|
|
|
|
|
privateKeys.add(privkey);
|
|
|
|
|
|
|
|
utxos.add(
|
|
|
|
UtxoWithAddress(
|
|
|
|
utxo: BitcoinUtxo(
|
|
|
|
txHash: utx.hash,
|
|
|
|
value: BigInt.from(utx.value),
|
|
|
|
vout: utx.vout,
|
|
|
|
scriptType: _getScriptType(address),
|
|
|
|
),
|
|
|
|
ownerDetails:
|
|
|
|
UtxoAddressDetails(publicKey: privkey.getPublic().toHex(), address: address),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
bool amountIsAcquired = !sendAll && leftAmount <= 0;
|
|
|
|
if ((inputsCount == null && amountIsAcquired) || inputsCount == i + 1) {
|
|
|
|
break;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
if (utxos.isEmpty) {
|
2021-12-24 12:52:08 +00:00
|
|
|
throw BitcoinTransactionNoInputsException();
|
|
|
|
}
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
var changeValue = allInputsAmount - credentialsAmount;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
if (!sendAll) {
|
|
|
|
if (changeValue > 0) {
|
|
|
|
final changeAddress = await walletAddresses.getChangeAddress();
|
|
|
|
final address = _addressTypeFromStr(changeAddress, network);
|
|
|
|
outputAddresses.add(address);
|
|
|
|
outputs.add(BitcoinOutput(address: address, value: BigInt.from(changeValue)));
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
2024-03-04 19:42:57 +00:00
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
final estimatedSize = BitcoinTransactionBuilder.estimateTransactionSize(
|
|
|
|
utxos: utxos, outputs: outputs, network: network);
|
2022-07-28 17:03:16 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
final fee = transactionCredentials.feeRate != null
|
|
|
|
? feeAmountWithFeeRate(transactionCredentials.feeRate!, 0, 0, size: estimatedSize)
|
|
|
|
: feeAmountForPriority(transactionCredentials.priority!, 0, 0, size: estimatedSize);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
if (fee == 0) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
var amount = credentialsAmount;
|
2022-07-28 17:03:16 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
final lastOutput = outputs.last;
|
|
|
|
if (!sendAll) {
|
|
|
|
if (changeValue > fee) {
|
|
|
|
// Here, lastOutput is change, deduct the fee from it
|
|
|
|
outputs[outputs.length - 1] =
|
|
|
|
BitcoinOutput(address: lastOutput.address, value: lastOutput.value - BigInt.from(fee));
|
2022-07-28 17:03:16 +00:00
|
|
|
}
|
2024-03-04 19:42:57 +00:00
|
|
|
} else {
|
|
|
|
// Here, if sendAll, the output amount equals to the input value - fee to fully spend every input on the transaction and have no amount for change
|
|
|
|
amount = allInputsAmount - fee;
|
|
|
|
outputs[outputs.length - 1] =
|
|
|
|
BitcoinOutput(address: lastOutput.address, value: BigInt.from(amount));
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
final totalAmount = amount + fee;
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
if (totalAmount > balance[currency]!.confirmed) {
|
2021-12-24 12:52:08 +00:00
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
if (totalAmount > allInputsAmount) {
|
|
|
|
if (unspentCoins.where((utx) => utx.isSending).length == utxos.length) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
} else {
|
|
|
|
if (changeValue > fee) {
|
|
|
|
outputAddresses.removeLast();
|
|
|
|
outputs.removeLast();
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
2024-03-04 19:42:57 +00:00
|
|
|
|
|
|
|
return _estimateTxFeeAndInputsToUse(
|
|
|
|
credentialsAmount, sendAll, outputAddresses, outputs, transactionCredentials,
|
|
|
|
inputsCount: utxos.length + 1);
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
return EstimatedTxResult(utxos: utxos, privateKeys: privateKeys, fee: fee, amount: amount);
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
@override
|
|
|
|
Future<PendingTransaction> createTransaction(Object credentials) async {
|
|
|
|
try {
|
|
|
|
final outputs = <BitcoinOutput>[];
|
|
|
|
final outputAddresses = <BitcoinBaseAddress>[];
|
|
|
|
final transactionCredentials = credentials as BitcoinTransactionCredentials;
|
|
|
|
final hasMultiDestination = transactionCredentials.outputs.length > 1;
|
|
|
|
final sendAll = !hasMultiDestination && transactionCredentials.outputs.first.sendAll;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
var credentialsAmount = 0;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
for (final out in transactionCredentials.outputs) {
|
|
|
|
final outputAddress = out.isParsedAddress ? out.extractedAddress! : out.address;
|
|
|
|
final address = _addressTypeFromStr(outputAddress, network);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
outputAddresses.add(address);
|
2022-07-28 17:03:16 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
if (hasMultiDestination) {
|
|
|
|
if (out.sendAll || out.formattedCryptoAmount! <= 0) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException(currency);
|
|
|
|
}
|
2023-06-16 01:14:01 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
final outputAmount = out.formattedCryptoAmount!;
|
|
|
|
credentialsAmount += outputAmount;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
outputs.add(BitcoinOutput(address: address, value: BigInt.from(outputAmount)));
|
|
|
|
} else {
|
|
|
|
if (!sendAll) {
|
|
|
|
final outputAmount = out.formattedCryptoAmount!;
|
|
|
|
credentialsAmount += outputAmount;
|
|
|
|
outputs.add(BitcoinOutput(address: address, value: BigInt.from(outputAmount)));
|
|
|
|
} else {
|
|
|
|
// The value will be changed after estimating the Tx size and deducting the fee from the total
|
|
|
|
outputs.add(BitcoinOutput(address: address, value: BigInt.from(0)));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
final estimatedTx = await _estimateTxFeeAndInputsToUse(
|
|
|
|
credentialsAmount, sendAll, outputAddresses, outputs, transactionCredentials);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
final txb = BitcoinTransactionBuilder(
|
|
|
|
utxos: estimatedTx.utxos,
|
|
|
|
outputs: outputs,
|
|
|
|
fee: BigInt.from(estimatedTx.fee),
|
|
|
|
network: network);
|
|
|
|
|
|
|
|
final transaction = txb.buildTransaction((txDigest, utxo, publicKey, sighash) {
|
|
|
|
final key = estimatedTx.privateKeys
|
|
|
|
.firstWhereOrNull((element) => element.getPublic().toHex() == publicKey);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
if (key == null) {
|
|
|
|
throw Exception("Cannot find private key");
|
|
|
|
}
|
|
|
|
|
|
|
|
if (utxo.utxo.isP2tr()) {
|
|
|
|
return key.signTapRoot(txDigest, sighash: sighash);
|
|
|
|
} else {
|
|
|
|
return key.signInput(txDigest, sigHash: sighash);
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
});
|
2024-03-04 19:42:57 +00:00
|
|
|
|
|
|
|
return PendingBitcoinTransaction(transaction, type,
|
|
|
|
electrumClient: electrumClient,
|
|
|
|
amount: estimatedTx.amount,
|
|
|
|
fee: estimatedTx.fee,
|
|
|
|
network: network)
|
|
|
|
..addListener((transaction) async {
|
|
|
|
transactionHistory.addOne(transaction);
|
|
|
|
await updateBalance();
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
throw e;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
String toJSON() => json.encode({
|
2023-11-15 23:12:23 +00:00
|
|
|
'mnemonic': mnemonic,
|
2024-03-04 19:42:57 +00:00
|
|
|
'account_index': walletAddresses.currentReceiveAddressIndexByType,
|
|
|
|
'change_address_index': walletAddresses.currentChangeAddressIndexByType,
|
|
|
|
'addresses': walletAddresses.allAddresses.map((addr) => addr.toJSON()).toList(),
|
|
|
|
'address_page_type': walletInfo.addressPageType == null
|
|
|
|
? SegwitAddresType.p2wpkh.toString()
|
|
|
|
: walletInfo.addressPageType.toString(),
|
|
|
|
'balance': balance[currency]?.toJSON(),
|
|
|
|
'network_type': network == BitcoinNetwork.testnet ? 'testnet' : 'mainnet',
|
2023-11-15 23:12:23 +00:00
|
|
|
});
|
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;
|
2023-10-12 22:50:16 +00:00
|
|
|
} catch (_) {
|
2022-01-13 14:48:42 +00:00
|
|
|
return 0;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
int feeAmountForPriority(BitcoinTransactionPriority priority, int inputsCount, int outputsCount,
|
|
|
|
{int? size}) =>
|
|
|
|
feeRate(priority) * (size ?? estimatedTransactionSize(inputsCount, outputsCount));
|
2021-12-24 12:52:08 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
int feeAmountWithFeeRate(int feeRate, int inputsCount, int outputsCount, {int? size}) =>
|
|
|
|
feeRate * (size ?? estimatedTransactionSize(inputsCount, outputsCount));
|
2022-07-28 17:03:16 +00:00
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
@override
|
2024-03-04 19:42:57 +00:00
|
|
|
int calculateEstimatedFee(TransactionPriority? priority, int? amount,
|
|
|
|
{int? outputsCount, int? size}) {
|
2021-12-24 12:52:08 +00:00
|
|
|
if (priority is BitcoinTransactionPriority) {
|
2023-10-12 22:50:16 +00:00
|
|
|
return calculateEstimatedFeeWithFeeRate(feeRate(priority), amount,
|
2024-03-04 19:42:57 +00:00
|
|
|
outputsCount: outputsCount, size: size);
|
2022-07-28 17:03:16 +00:00
|
|
|
}
|
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
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
int calculateEstimatedFeeWithFeeRate(int feeRate, int? amount, {int? outputsCount, int? size}) {
|
|
|
|
if (size != null) {
|
|
|
|
return feeAmountWithFeeRate(feeRate, 0, 0, size: size);
|
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
|
2023-10-12 22:50:16 +00:00
|
|
|
return feeAmountWithFeeRate(feeRate, inputsCount, _outputsCount);
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> save() async {
|
|
|
|
final path = await makePath();
|
2023-04-10 23:16:13 +00:00
|
|
|
await encryptionFileUtils.write(path: path, password: _password, data: toJSON());
|
2021-12-24 12:52:08 +00:00
|
|
|
await transactionHistory.save();
|
|
|
|
}
|
|
|
|
|
2023-08-04 17:01:49 +00:00
|
|
|
@override
|
2023-07-12 23:20:11 +00:00
|
|
|
Future<void> renameWalletFiles(String newWalletName) async {
|
|
|
|
final currentWalletPath = await pathForWallet(name: walletInfo.name, type: type);
|
|
|
|
final currentWalletFile = File(currentWalletPath);
|
|
|
|
|
2023-10-12 22:50:16 +00:00
|
|
|
final currentDirPath = await pathForWalletDir(name: walletInfo.name, type: type);
|
2023-07-12 23:20:11 +00:00
|
|
|
final currentTransactionsFile = File('$currentDirPath/$transactionsHistoryFileName');
|
|
|
|
|
|
|
|
// Copies current wallet files into new wallet name's dir and files
|
|
|
|
if (currentWalletFile.existsSync()) {
|
|
|
|
final newWalletPath = await pathForWallet(name: newWalletName, type: type);
|
|
|
|
await currentWalletFile.copy(newWalletPath);
|
|
|
|
}
|
|
|
|
if (currentTransactionsFile.existsSync()) {
|
|
|
|
final newDirPath = await pathForWalletDir(name: newWalletName, type: type);
|
|
|
|
await currentTransactionsFile.copy('$newDirPath/$transactionsHistoryFileName');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete old name's dir and files
|
|
|
|
await Directory(currentDirPath).delete(recursive: true);
|
|
|
|
}
|
|
|
|
|
2022-07-19 14:29:28 +00:00
|
|
|
@override
|
|
|
|
Future<void> changePassword(String password) async {
|
|
|
|
_password = password;
|
|
|
|
await save();
|
|
|
|
await transactionHistory.changePassword(password);
|
|
|
|
}
|
|
|
|
|
2021-12-24 12:52:08 +00:00
|
|
|
@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 (_) {}
|
|
|
|
}
|
|
|
|
|
2023-10-12 22:50:16 +00:00
|
|
|
Future<String> makePath() async => pathForWallet(name: walletInfo.name, type: walletInfo.type);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
Future<void> updateUnspent() async {
|
2024-03-04 19:42:57 +00:00
|
|
|
List<BitcoinUnspent> updatedUnspentCoins = [];
|
|
|
|
|
|
|
|
final addressesSet = walletAddresses.allAddresses.map((addr) => addr.address).toSet();
|
|
|
|
|
|
|
|
await Future.wait(walletAddresses.allAddresses.map((address) => electrumClient
|
|
|
|
.getListUnspentWithAddress(address.address, network)
|
|
|
|
.then((unspent) => Future.forEach<Map<String, dynamic>>(unspent, (unspent) async {
|
2023-11-15 23:12:23 +00:00
|
|
|
try {
|
2024-03-04 19:42:57 +00:00
|
|
|
final coin = BitcoinUnspent.fromJSON(address, unspent);
|
|
|
|
final tx = await fetchTransactionInfo(
|
|
|
|
hash: coin.hash, height: 0, myAddresses: addressesSet);
|
|
|
|
coin.isChange = tx?.direction == TransactionDirection.outgoing;
|
|
|
|
updatedUnspentCoins.add(coin);
|
|
|
|
} catch (_) {}
|
|
|
|
}))));
|
|
|
|
|
|
|
|
unspentCoins = updatedUnspentCoins;
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
if (unspentCoinsInfo.isEmpty) {
|
|
|
|
unspentCoins.forEach((coin) => _addCoinInfo(coin));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (unspentCoins.isNotEmpty) {
|
|
|
|
unspentCoins.forEach((coin) {
|
2024-03-04 19:42:57 +00:00
|
|
|
final coinInfoList = unspentCoinsInfo.values.where((element) =>
|
|
|
|
element.walletId.contains(id) &&
|
|
|
|
element.hash.contains(coin.hash) &&
|
|
|
|
element.vout == coin.vout);
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
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(
|
2023-10-12 22:50:16 +00:00
|
|
|
walletId: id,
|
|
|
|
hash: coin.hash,
|
|
|
|
isFrozen: coin.isFrozen,
|
|
|
|
isSending: coin.isSending,
|
|
|
|
noteRaw: coin.note,
|
|
|
|
address: coin.bitcoinAddressRecord.address,
|
|
|
|
value: coin.value,
|
|
|
|
vout: coin.vout,
|
2023-11-15 23:12:23 +00:00
|
|
|
isChange: coin.isChange,
|
2021-12-24 12:52:08 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
await unspentCoinsInfo.add(newInfo);
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _refreshUnspentCoinsInfo() async {
|
|
|
|
try {
|
|
|
|
final List<dynamic> keys = <dynamic>[];
|
2023-10-12 22:50:16 +00:00
|
|
|
final currentWalletUnspentCoins =
|
2023-11-15 23:12:23 +00:00
|
|
|
unspentCoinsInfo.values.where((element) => element.walletId.contains(id));
|
2021-12-24 12:52:08 +00:00
|
|
|
|
|
|
|
if (currentWalletUnspentCoins.isNotEmpty) {
|
|
|
|
currentWalletUnspentCoins.forEach((element) {
|
2024-03-04 19:42:57 +00:00
|
|
|
final existUnspentCoins = unspentCoins
|
|
|
|
.where((coin) => element.hash.contains(coin.hash) && element.vout == coin.vout);
|
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 {
|
2024-03-04 19:42:57 +00:00
|
|
|
String transactionHex;
|
|
|
|
int? time;
|
|
|
|
int confirmations = 0;
|
|
|
|
if (network == BitcoinNetwork.testnet) {
|
|
|
|
// Testnet public electrum server does not support verbose transaction fetching
|
|
|
|
transactionHex = await electrumClient.getTransactionHex(hash: hash);
|
|
|
|
|
|
|
|
final status = json.decode(
|
|
|
|
(await http.get(Uri.parse("https://blockstream.info/testnet/api/tx/$hash/status"))).body);
|
|
|
|
|
|
|
|
time = status["block_time"] as int?;
|
|
|
|
final tip = await electrumClient.getCurrentBlockChainTip() ?? 0;
|
|
|
|
confirmations = tip - (status["block_height"] as int? ?? 0);
|
|
|
|
} else {
|
|
|
|
final verboseTransaction = await electrumClient.getTransactionRaw(hash: hash);
|
|
|
|
|
|
|
|
transactionHex = verboseTransaction['hex'] as String;
|
|
|
|
time = verboseTransaction['time'] as int?;
|
|
|
|
confirmations = verboseTransaction['confirmations'] as int? ?? 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
final original = bitcoin_base.BtcTransaction.fromRaw(transactionHex);
|
|
|
|
final ins = <bitcoin_base.BtcTransaction>[];
|
|
|
|
|
|
|
|
for (final vin in original.inputs) {
|
|
|
|
final txHex = await electrumClient.getTransactionHex(hash: vin.txId);
|
|
|
|
final tx = bitcoin_base.BtcTransaction.fromRaw(txHex);
|
2022-01-17 15:33:51 +00:00
|
|
|
ins.add(tx);
|
|
|
|
}
|
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
return ElectrumTransactionBundle(original,
|
|
|
|
ins: ins, time: time, confirmations: confirmations, height: height);
|
2022-01-17 15:33:51 +00:00
|
|
|
}
|
|
|
|
|
2022-10-17 20:55:41 +00:00
|
|
|
Future<ElectrumTransactionInfo?> fetchTransactionInfo(
|
2024-03-04 19:42:57 +00:00
|
|
|
{required String hash,
|
|
|
|
required int height,
|
|
|
|
required Set<String> myAddresses,
|
|
|
|
bool? retryOnFailure}) async {
|
2023-10-12 22:50:16 +00:00
|
|
|
try {
|
2024-03-04 19:42:57 +00:00
|
|
|
return ElectrumTransactionInfo.fromElectrumBundle(
|
|
|
|
await getTransactionExpanded(hash: hash, height: height), walletInfo.type, network,
|
|
|
|
addresses: myAddresses, height: height);
|
|
|
|
} catch (e) {
|
|
|
|
if (e is FormatException && retryOnFailure == true) {
|
|
|
|
await Future.delayed(const Duration(seconds: 2));
|
|
|
|
return fetchTransactionInfo(hash: hash, height: height, myAddresses: myAddresses);
|
|
|
|
}
|
2023-10-12 22:50:16 +00:00
|
|
|
return null;
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<Map<String, ElectrumTransactionInfo>> fetchTransactions() async {
|
2024-01-23 05:15:24 +00:00
|
|
|
try {
|
2024-03-04 19:42:57 +00:00
|
|
|
final Map<String, ElectrumTransactionInfo> historiesWithDetails = {};
|
|
|
|
final addressesSet = walletAddresses.allAddresses.map((addr) => addr.address).toSet();
|
|
|
|
final currentHeight = await electrumClient.getCurrentBlockChainTip() ?? 0;
|
|
|
|
|
|
|
|
await Future.wait(ADDRESS_TYPES.map((type) {
|
|
|
|
final addressesByType = walletAddresses.allAddresses.where((addr) => addr.type == type);
|
|
|
|
|
|
|
|
return Future.wait(addressesByType.map((addressRecord) async {
|
|
|
|
final history = await _fetchAddressHistory(addressRecord, addressesSet, currentHeight);
|
|
|
|
|
|
|
|
if (history.isNotEmpty) {
|
|
|
|
addressRecord.txCount = history.length;
|
|
|
|
historiesWithDetails.addAll(history);
|
|
|
|
|
|
|
|
final matchedAddresses =
|
|
|
|
addressesByType.where((addr) => addr.isHidden == addressRecord.isHidden);
|
|
|
|
|
|
|
|
final isLastUsedAddress =
|
|
|
|
history.isNotEmpty && addressRecord.address == matchedAddresses.last.address;
|
|
|
|
|
|
|
|
if (isLastUsedAddress) {
|
|
|
|
await walletAddresses.discoverAddresses(
|
|
|
|
matchedAddresses.toList(),
|
|
|
|
addressRecord.isHidden,
|
|
|
|
(address, addressesSet) =>
|
|
|
|
_fetchAddressHistory(address, addressesSet, currentHeight)
|
|
|
|
.then((history) => history.isNotEmpty ? address.address : null),
|
|
|
|
type: type);
|
|
|
|
}
|
2024-01-23 05:15:24 +00:00
|
|
|
}
|
2024-03-04 19:42:57 +00:00
|
|
|
}));
|
|
|
|
}));
|
2024-01-23 05:15:24 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
return historiesWithDetails;
|
|
|
|
} catch (e) {
|
|
|
|
print(e.toString());
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
}
|
2024-01-23 05:15:24 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
Future<Map<String, ElectrumTransactionInfo>> _fetchAddressHistory(
|
|
|
|
BitcoinAddressRecord addressRecord, Set<String> addressesSet, int currentHeight) async {
|
|
|
|
try {
|
|
|
|
final Map<String, ElectrumTransactionInfo> historiesWithDetails = {};
|
|
|
|
|
|
|
|
final history = await electrumClient
|
|
|
|
.getHistory(addressRecord.scriptHash ?? addressRecord.updateScriptHash(network));
|
|
|
|
|
|
|
|
if (history.isNotEmpty) {
|
|
|
|
addressRecord.setAsUsed();
|
|
|
|
|
|
|
|
await Future.wait(history.map((transaction) async {
|
|
|
|
final txid = transaction['tx_hash'] as String;
|
|
|
|
final height = transaction['height'] as int;
|
|
|
|
final storedTx = transactionHistory.transactions[txid];
|
|
|
|
|
|
|
|
if (storedTx != null) {
|
|
|
|
if (height > 0) {
|
|
|
|
storedTx.height = height;
|
|
|
|
// the tx's block itself is the first confirmation so add 1
|
|
|
|
storedTx.confirmations = currentHeight - height + 1;
|
|
|
|
storedTx.isPending = storedTx.confirmations == 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
historiesWithDetails[txid] = storedTx;
|
|
|
|
} else {
|
|
|
|
final tx = await fetchTransactionInfo(
|
|
|
|
hash: txid, height: height, myAddresses: addressesSet, retryOnFailure: true);
|
|
|
|
|
|
|
|
if (tx != null) {
|
|
|
|
historiesWithDetails[txid] = tx;
|
|
|
|
|
|
|
|
// Got a new transaction fetched, add it to the transaction history
|
|
|
|
// instead of waiting all to finish, and next time it will be faster
|
|
|
|
transactionHistory.addOne(tx);
|
|
|
|
await transactionHistory.save();
|
|
|
|
}
|
|
|
|
}
|
2024-01-23 05:15:24 +00:00
|
|
|
|
|
|
|
return Future.value(null);
|
2024-03-04 19:42:57 +00:00
|
|
|
}));
|
|
|
|
}
|
2024-01-23 05:15:24 +00:00
|
|
|
|
2024-03-04 19:42:57 +00:00
|
|
|
return historiesWithDetails;
|
2024-01-23 05:15:24 +00:00
|
|
|
} catch (e) {
|
|
|
|
print(e.toString());
|
|
|
|
return {};
|
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> updateTransactions() async {
|
|
|
|
try {
|
|
|
|
if (_isTransactionUpdating) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
_isTransactionUpdating = true;
|
2024-03-04 19:42:57 +00:00
|
|
|
await fetchTransactions();
|
2022-01-24 12:04:23 +00:00
|
|
|
walletAddresses.updateReceiveAddresses();
|
2021-12-24 12:52:08 +00:00
|
|
|
_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 updateUnspent();
|
2023-04-20 13:46:41 +00:00
|
|
|
await updateBalance();
|
2021-12-24 12:52:08 +00:00
|
|
|
await updateTransactions();
|
2023-06-16 01:14:01 +00:00
|
|
|
} catch (e, s) {
|
2021-12-24 12:52:08 +00:00
|
|
|
print(e.toString());
|
2023-06-16 01:14:01 +00:00
|
|
|
_onError?.call(FlutterErrorDetails(
|
|
|
|
exception: e,
|
|
|
|
stack: s,
|
|
|
|
library: this.runtimeType.toString(),
|
|
|
|
));
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<ElectrumBalance> _fetchBalances() async {
|
2024-03-04 19:42:57 +00:00
|
|
|
final addresses = walletAddresses.allAddresses.toList();
|
2022-01-18 16:27:33 +00:00
|
|
|
final balanceFutures = <Future<Map<String, dynamic>>>[];
|
|
|
|
for (var i = 0; i < addresses.length; i++) {
|
2023-11-15 23:12:23 +00:00
|
|
|
final addressRecord = addresses[i];
|
2024-03-04 19:42:57 +00:00
|
|
|
final sh = scriptHash(addressRecord.address, network: network);
|
2022-01-18 16:27:33 +00:00
|
|
|
final balanceFuture = electrumClient.getBalance(sh);
|
|
|
|
balanceFutures.add(balanceFuture);
|
2023-04-20 13:46:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var totalFrozen = 0;
|
|
|
|
unspentCoinsInfo.values.forEach((info) {
|
|
|
|
unspentCoins.forEach((element) {
|
2023-10-12 22:50:16 +00:00
|
|
|
if (element.hash == info.hash &&
|
2024-03-04 19:42:57 +00:00
|
|
|
element.vout == info.vout &&
|
2023-10-12 22:50:16 +00:00
|
|
|
info.isFrozen &&
|
|
|
|
element.bitcoinAddressRecord.address == info.address &&
|
|
|
|
element.value == info.value) {
|
2023-04-20 13:46:41 +00:00
|
|
|
totalFrozen += element.value;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
2022-01-18 16:27:33 +00:00
|
|
|
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-12 22:50:16 +00:00
|
|
|
return ElectrumBalance(
|
|
|
|
confirmed: totalConfirmed, unconfirmed: totalUnconfirmed, frozen: totalFrozen);
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
|
|
|
|
2023-04-20 13:46:41 +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();
|
2024-03-04 19:42:57 +00:00
|
|
|
var addresses = walletAddresses.allAddresses.where((addr) => addr.isHidden).toList();
|
2022-01-12 13:20:43 +00:00
|
|
|
|
|
|
|
if (addresses.length < minCountOfHiddenAddresses) {
|
2024-03-04 19:42:57 +00:00
|
|
|
addresses = walletAddresses.allAddresses.toList();
|
2022-01-12 13:20:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return addresses[random.nextInt(addresses.length)].address;
|
|
|
|
}
|
2023-06-16 01:14:01 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
void setExceptionHandler(void Function(FlutterErrorDetails) onError) => _onError = onError;
|
2023-09-14 19:14:49 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
String signMessage(String message, {String? address = null}) {
|
|
|
|
final index = address != null
|
2024-03-04 19:42:57 +00:00
|
|
|
? walletAddresses.allAddresses.firstWhere((element) => element.address == address).index
|
2023-09-14 19:14:49 +00:00
|
|
|
: null;
|
2023-12-08 14:05:52 +00:00
|
|
|
final HD = index == null ? hd : hd.derive(index);
|
|
|
|
return base64Encode(HD.signMessage(message));
|
2023-09-14 19:14:49 +00:00
|
|
|
}
|
2021-12-24 12:52:08 +00:00
|
|
|
}
|
2024-03-04 19:42:57 +00:00
|
|
|
|
|
|
|
class EstimateTxParams {
|
|
|
|
EstimateTxParams(
|
|
|
|
{required this.amount,
|
|
|
|
required this.feeRate,
|
|
|
|
required this.priority,
|
|
|
|
required this.outputsCount,
|
|
|
|
required this.size});
|
|
|
|
|
|
|
|
final int amount;
|
|
|
|
final int feeRate;
|
|
|
|
final TransactionPriority priority;
|
|
|
|
final int outputsCount;
|
|
|
|
final int size;
|
|
|
|
}
|
|
|
|
|
|
|
|
class EstimatedTxResult {
|
|
|
|
EstimatedTxResult(
|
|
|
|
{required this.utxos, required this.privateKeys, required this.fee, required this.amount});
|
|
|
|
|
|
|
|
final List<UtxoWithAddress> utxos;
|
|
|
|
final List<ECPrivate> privateKeys;
|
|
|
|
final int fee;
|
|
|
|
final int amount;
|
|
|
|
}
|
|
|
|
|
|
|
|
BitcoinBaseAddress _addressTypeFromStr(String address, BasedUtxoNetwork network) {
|
|
|
|
if (P2pkhAddress.regex.hasMatch(address)) {
|
|
|
|
return P2pkhAddress.fromAddress(address: address, network: network);
|
|
|
|
} else if (P2shAddress.regex.hasMatch(address)) {
|
|
|
|
return P2shAddress.fromAddress(address: address, network: network);
|
|
|
|
} else if (P2wshAddress.regex.hasMatch(address)) {
|
|
|
|
return P2wshAddress.fromAddress(address: address, network: network);
|
|
|
|
} else if (P2trAddress.regex.hasMatch(address)) {
|
|
|
|
return P2trAddress.fromAddress(address: address, network: network);
|
|
|
|
} else {
|
|
|
|
return P2wpkhAddress.fromAddress(address: address, network: network);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
BitcoinAddressType _getScriptType(BitcoinBaseAddress type) {
|
|
|
|
if (type is P2pkhAddress) {
|
|
|
|
return P2pkhAddressType.p2pkh;
|
|
|
|
} else if (type is P2shAddress) {
|
|
|
|
return P2shAddressType.p2wpkhInP2sh;
|
|
|
|
} else if (type is P2wshAddress) {
|
|
|
|
return SegwitAddresType.p2wsh;
|
|
|
|
} else if (type is P2trAddress) {
|
|
|
|
return SegwitAddresType.p2tr;
|
|
|
|
} else {
|
|
|
|
return SegwitAddresType.p2wpkh;
|
|
|
|
}
|
|
|
|
}
|