2024-01-14 19:03:07 +00:00
|
|
|
import 'dart:async';
|
2023-11-07 18:19:42 +00:00
|
|
|
import 'dart:math';
|
2024-04-15 21:48:55 +00:00
|
|
|
import 'dart:typed_data';
|
2023-09-18 21:28:31 +00:00
|
|
|
|
2023-11-07 18:19:42 +00:00
|
|
|
import 'package:coinlib_flutter/coinlib_flutter.dart' as coinlib;
|
2023-11-03 19:46:55 +00:00
|
|
|
import 'package:isar/isar.dart';
|
2024-06-04 21:07:31 +00:00
|
|
|
|
2024-05-23 00:37:06 +00:00
|
|
|
import '../../../electrumx_rpc/cached_electrumx_client.dart';
|
|
|
|
import '../../../electrumx_rpc/client_manager.dart';
|
|
|
|
import '../../../electrumx_rpc/electrumx_client.dart';
|
|
|
|
import '../../../models/isar/models/blockchain_data/v2/input_v2.dart';
|
|
|
|
import '../../../models/isar/models/blockchain_data/v2/output_v2.dart';
|
|
|
|
import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart';
|
|
|
|
import '../../../models/isar/models/isar_models.dart';
|
|
|
|
import '../../../models/paymint/fee_object_model.dart';
|
|
|
|
import '../../../models/signing_data.dart';
|
|
|
|
import '../../../utilities/amount/amount.dart';
|
|
|
|
import '../../../utilities/enums/derive_path_type_enum.dart';
|
|
|
|
import '../../../utilities/enums/fee_rate_type_enum.dart';
|
|
|
|
import '../../../utilities/extensions/extensions.dart';
|
|
|
|
import '../../../utilities/logger.dart';
|
|
|
|
import '../../../utilities/paynym_is_api.dart';
|
|
|
|
import '../../crypto_currency/coins/firo.dart';
|
|
|
|
import '../../crypto_currency/interfaces/electrumx_currency_interface.dart';
|
|
|
|
import '../../models/tx_data.dart';
|
|
|
|
import '../impl/bitcoin_wallet.dart';
|
|
|
|
import '../impl/peercoin_wallet.dart';
|
|
|
|
import '../intermediate/bip39_hd_wallet.dart';
|
|
|
|
import 'paynym_interface.dart';
|
2023-09-18 21:28:31 +00:00
|
|
|
|
2024-05-15 21:20:45 +00:00
|
|
|
mixin ElectrumXInterface<T extends ElectrumXCurrencyInterface>
|
|
|
|
on Bip39HDWallet<T> {
|
2023-11-14 20:31:53 +00:00
|
|
|
late ElectrumXClient electrumXClient;
|
|
|
|
late CachedElectrumXClient electrumXCachedClient;
|
2023-09-18 21:28:31 +00:00
|
|
|
|
2024-01-17 17:12:36 +00:00
|
|
|
int? get maximumFeerate => null;
|
|
|
|
|
2024-01-14 17:26:52 +00:00
|
|
|
static const _kServerBatchCutoffVersion = [1, 6];
|
|
|
|
List<int>? _serverVersion;
|
2024-05-07 00:25:31 +00:00
|
|
|
Future<bool> get serverCanBatch async {
|
2024-01-14 17:26:52 +00:00
|
|
|
// Firo server added batching without incrementing version number...
|
|
|
|
if (cryptoCurrency is Firo) {
|
|
|
|
return true;
|
|
|
|
}
|
2024-05-07 00:25:31 +00:00
|
|
|
|
|
|
|
try {
|
2024-05-15 21:20:45 +00:00
|
|
|
_serverVersion ??= _parseServerVersion(
|
|
|
|
(await electrumXClient
|
|
|
|
.getServerFeatures()
|
|
|
|
.timeout(const Duration(seconds: 2)))["server_version"] as String,
|
|
|
|
);
|
2024-05-07 00:25:31 +00:00
|
|
|
} catch (_) {
|
|
|
|
// ignore failure as it doesn't matter
|
|
|
|
}
|
|
|
|
|
2024-01-14 17:26:52 +00:00
|
|
|
if (_serverVersion != null && _serverVersion!.length > 2) {
|
|
|
|
if (_serverVersion![0] > _kServerBatchCutoffVersion[0]) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
if (_serverVersion![1] > _kServerBatchCutoffVersion[1]) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
2023-11-14 19:21:21 +00:00
|
|
|
|
2024-01-05 19:45:42 +00:00
|
|
|
Future<List<({String address, Amount amount, bool isChange})>>
|
2024-06-04 21:07:31 +00:00
|
|
|
_helperRecipientsConvert(
|
|
|
|
List<String> addrs,
|
|
|
|
List<BigInt> satValues,
|
|
|
|
) async {
|
2024-01-05 19:45:42 +00:00
|
|
|
final List<({String address, Amount amount, bool isChange})> results = [];
|
2023-11-08 19:57:38 +00:00
|
|
|
|
|
|
|
for (int i = 0; i < addrs.length; i++) {
|
2024-01-05 19:45:42 +00:00
|
|
|
results.add(
|
|
|
|
(
|
|
|
|
address: addrs[i],
|
|
|
|
amount: Amount(
|
2024-06-04 21:07:31 +00:00
|
|
|
rawValue: satValues[i],
|
2024-01-05 19:45:42 +00:00
|
|
|
fractionDigits: cryptoCurrency.fractionDigits,
|
|
|
|
),
|
|
|
|
isChange: (await mainDB.isar.addresses
|
|
|
|
.where()
|
|
|
|
.walletIdEqualTo(walletId)
|
|
|
|
.filter()
|
|
|
|
.subTypeEqualTo(AddressSubType.change)
|
|
|
|
.and()
|
|
|
|
.valueEqualTo(addrs[i])
|
|
|
|
.valueProperty()
|
|
|
|
.findFirst()) !=
|
|
|
|
null
|
2023-11-08 19:57:38 +00:00
|
|
|
),
|
2024-01-05 19:45:42 +00:00
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<TxData> coinSelection({
|
|
|
|
required TxData txData,
|
|
|
|
required bool coinControl,
|
|
|
|
required bool isSendAll,
|
|
|
|
int additionalOutputs = 0,
|
|
|
|
List<UTXO>? utxos,
|
|
|
|
}) async {
|
|
|
|
Logging.instance
|
|
|
|
.log("Starting coinSelection ----------", level: LogLevel.Info);
|
|
|
|
|
|
|
|
// TODO: multiple recipients one day
|
|
|
|
assert(txData.recipients!.length == 1);
|
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
if (coinControl && utxos == null) {
|
|
|
|
throw Exception("Coin control used where utxos is null!");
|
|
|
|
}
|
|
|
|
|
2023-11-08 19:57:38 +00:00
|
|
|
final recipientAddress = txData.recipients!.first.address;
|
2024-06-04 21:07:31 +00:00
|
|
|
final satoshiAmountToSend = txData.amount!.raw;
|
2023-11-08 19:57:38 +00:00
|
|
|
final int? satsPerVByte = txData.satsPerVByte;
|
|
|
|
final selectedTxFeeRate = txData.feeRateAmount!;
|
|
|
|
|
|
|
|
final List<UTXO> availableOutputs =
|
|
|
|
utxos ?? await mainDB.getUTXOs(walletId).findAll();
|
|
|
|
final currentChainHeight = await chainHeight;
|
2024-06-04 21:07:31 +00:00
|
|
|
|
|
|
|
final spendableOutputs = availableOutputs
|
|
|
|
.where(
|
|
|
|
(e) =>
|
|
|
|
!e.isBlocked &&
|
|
|
|
(e.used != true) &&
|
|
|
|
e.isConfirmed(currentChainHeight, cryptoCurrency.minConfirms),
|
|
|
|
)
|
|
|
|
.toList();
|
|
|
|
final spendableSatoshiValue =
|
|
|
|
spendableOutputs.fold(BigInt.zero, (p, e) => p + BigInt.from(e.value));
|
|
|
|
|
|
|
|
if (spendableSatoshiValue < satoshiAmountToSend) {
|
|
|
|
throw Exception("Insufficient balance");
|
|
|
|
} else if (spendableSatoshiValue == satoshiAmountToSend && !isSendAll) {
|
|
|
|
throw Exception("Insufficient balance to pay transaction fee");
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (coinControl) {
|
|
|
|
if (spendableOutputs.length < availableOutputs.length) {
|
|
|
|
throw ArgumentError("Attempted to use an unavailable utxo");
|
|
|
|
}
|
2024-06-04 21:07:31 +00:00
|
|
|
// don't care about sorting if using all utxos
|
|
|
|
} else {
|
2023-11-08 19:57:38 +00:00
|
|
|
// sort spendable by age (oldest first)
|
2024-05-15 21:20:45 +00:00
|
|
|
spendableOutputs.sort(
|
|
|
|
(a, b) => (b.blockTime ?? currentChainHeight)
|
|
|
|
.compareTo((a.blockTime ?? currentChainHeight)),
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
2024-05-15 21:20:45 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
"spendableOutputs.length: ${spendableOutputs.length}",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
"availableOutputs.length: ${availableOutputs.length}",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance
|
|
|
|
.log("spendableOutputs: $spendableOutputs", level: LogLevel.Info);
|
2024-05-15 21:20:45 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
"spendableSatoshiValue: $spendableSatoshiValue",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance
|
|
|
|
.log("satoshiAmountToSend: $satoshiAmountToSend", level: LogLevel.Info);
|
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
BigInt satoshisBeingUsed = BigInt.zero;
|
2023-11-08 19:57:38 +00:00
|
|
|
int inputsBeingConsumed = 0;
|
2024-06-04 21:07:31 +00:00
|
|
|
final List<UTXO> utxoObjectsToUse = [];
|
2023-11-08 19:57:38 +00:00
|
|
|
|
|
|
|
if (!coinControl) {
|
|
|
|
for (var i = 0;
|
|
|
|
satoshisBeingUsed < satoshiAmountToSend &&
|
|
|
|
i < spendableOutputs.length;
|
|
|
|
i++) {
|
|
|
|
utxoObjectsToUse.add(spendableOutputs[i]);
|
2024-06-04 21:07:31 +00:00
|
|
|
satoshisBeingUsed += BigInt.from(spendableOutputs[i].value);
|
2023-11-08 19:57:38 +00:00
|
|
|
inputsBeingConsumed += 1;
|
|
|
|
}
|
|
|
|
for (int i = 0;
|
|
|
|
i < additionalOutputs &&
|
|
|
|
inputsBeingConsumed < spendableOutputs.length;
|
|
|
|
i++) {
|
|
|
|
utxoObjectsToUse.add(spendableOutputs[inputsBeingConsumed]);
|
2024-06-04 21:07:31 +00:00
|
|
|
satoshisBeingUsed +=
|
|
|
|
BigInt.from(spendableOutputs[inputsBeingConsumed].value);
|
2023-11-08 19:57:38 +00:00
|
|
|
inputsBeingConsumed += 1;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
satoshisBeingUsed = spendableSatoshiValue;
|
2024-06-04 21:07:31 +00:00
|
|
|
utxoObjectsToUse.addAll(spendableOutputs);
|
2023-11-08 19:57:38 +00:00
|
|
|
inputsBeingConsumed = spendableOutputs.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
Logging.instance
|
|
|
|
.log("satoshisBeingUsed: $satoshisBeingUsed", level: LogLevel.Info);
|
|
|
|
Logging.instance
|
|
|
|
.log("inputsBeingConsumed: $inputsBeingConsumed", level: LogLevel.Info);
|
|
|
|
Logging.instance
|
|
|
|
.log('utxoObjectsToUse: $utxoObjectsToUse', level: LogLevel.Info);
|
|
|
|
|
|
|
|
// numberOfOutputs' length must always be equal to that of recipientsArray and recipientsAmtArray
|
2024-05-07 00:25:10 +00:00
|
|
|
final List<String> recipientsArray = [recipientAddress];
|
2024-06-04 21:07:31 +00:00
|
|
|
final List<BigInt> recipientsAmtArray = [satoshiAmountToSend];
|
2023-11-08 19:57:38 +00:00
|
|
|
|
|
|
|
// gather required signing data
|
|
|
|
final utxoSigningData = await fetchBuildTxData(utxoObjectsToUse);
|
|
|
|
|
|
|
|
if (isSendAll) {
|
2024-06-04 21:07:31 +00:00
|
|
|
return await _sendAllBuilder(
|
|
|
|
txData: txData,
|
|
|
|
recipientAddress: recipientAddress,
|
|
|
|
satoshiAmountToSend: satoshiAmountToSend,
|
|
|
|
satoshisBeingUsed: satoshisBeingUsed,
|
2023-11-08 19:57:38 +00:00
|
|
|
utxoSigningData: utxoSigningData,
|
2024-06-04 21:07:31 +00:00
|
|
|
satsPerVByte: satsPerVByte,
|
|
|
|
feeRatePerKB: selectedTxFeeRate,
|
2023-11-08 19:57:38 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
final int vSizeForOneOutput;
|
|
|
|
try {
|
2024-01-05 18:59:01 +00:00
|
|
|
vSizeForOneOutput = (await buildTransaction(
|
2023-11-08 19:57:38 +00:00
|
|
|
utxoSigningData: utxoSigningData,
|
|
|
|
txData: txData.copyWith(
|
2024-01-05 19:45:42 +00:00
|
|
|
recipients: await _helperRecipientsConvert(
|
2023-11-08 19:57:38 +00:00
|
|
|
[recipientAddress],
|
2024-06-04 21:07:31 +00:00
|
|
|
[satoshisBeingUsed - BigInt.one],
|
2023-11-08 19:57:38 +00:00
|
|
|
),
|
|
|
|
),
|
2024-01-05 18:59:01 +00:00
|
|
|
))
|
|
|
|
.vSize!;
|
2023-11-08 19:57:38 +00:00
|
|
|
} catch (e) {
|
|
|
|
Logging.instance.log("vSizeForOneOutput: $e", level: LogLevel.Error);
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
|
|
|
|
final int vSizeForTwoOutPuts;
|
2024-06-04 21:07:31 +00:00
|
|
|
|
|
|
|
BigInt maxBI(BigInt a, BigInt b) => a > b ? a : b;
|
|
|
|
|
2023-11-08 19:57:38 +00:00
|
|
|
try {
|
2024-01-05 18:59:01 +00:00
|
|
|
vSizeForTwoOutPuts = (await buildTransaction(
|
2023-11-08 19:57:38 +00:00
|
|
|
utxoSigningData: utxoSigningData,
|
|
|
|
txData: txData.copyWith(
|
2024-01-05 19:45:42 +00:00
|
|
|
recipients: await _helperRecipientsConvert(
|
2023-11-08 19:57:38 +00:00
|
|
|
[recipientAddress, (await getCurrentChangeAddress())!.value],
|
|
|
|
[
|
|
|
|
satoshiAmountToSend,
|
2024-06-04 21:07:31 +00:00
|
|
|
maxBI(
|
|
|
|
BigInt.zero,
|
|
|
|
satoshisBeingUsed - (satoshiAmountToSend + BigInt.one),
|
|
|
|
),
|
2023-11-08 19:57:38 +00:00
|
|
|
],
|
|
|
|
),
|
|
|
|
),
|
2024-01-05 18:59:01 +00:00
|
|
|
))
|
|
|
|
.vSize!;
|
2023-11-08 19:57:38 +00:00
|
|
|
} catch (e) {
|
|
|
|
Logging.instance.log("vSizeForTwoOutPuts: $e", level: LogLevel.Error);
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Assume 1 output, only for recipient and no change
|
2024-06-04 21:07:31 +00:00
|
|
|
final feeForOneOutput = BigInt.from(
|
|
|
|
satsPerVByte != null
|
|
|
|
? (satsPerVByte * vSizeForOneOutput)
|
|
|
|
: estimateTxFee(
|
|
|
|
vSize: vSizeForOneOutput,
|
|
|
|
feeRatePerKB: selectedTxFeeRate,
|
|
|
|
),
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
// Assume 2 outputs, one for recipient and one for change
|
2024-06-04 21:07:31 +00:00
|
|
|
final feeForTwoOutputs = BigInt.from(
|
|
|
|
satsPerVByte != null
|
|
|
|
? (satsPerVByte * vSizeForTwoOutPuts)
|
|
|
|
: estimateTxFee(
|
|
|
|
vSize: vSizeForTwoOutPuts,
|
|
|
|
feeRatePerKB: selectedTxFeeRate,
|
|
|
|
),
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
"feeForTwoOutputs: $feeForTwoOutputs",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
"feeForOneOutput: $feeForOneOutput",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
|
|
|
|
final difference = satoshisBeingUsed - satoshiAmountToSend;
|
|
|
|
|
|
|
|
Future<TxData> singleOutputTxn() async {
|
|
|
|
Logging.instance.log(
|
|
|
|
'Input size: $satoshisBeingUsed',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
'Recipient output size: $satoshiAmountToSend',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
'Fee being paid: $difference sats',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
'Estimated fee: $feeForOneOutput',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
final txnData = await buildTransaction(
|
|
|
|
utxoSigningData: utxoSigningData,
|
|
|
|
txData: txData.copyWith(
|
|
|
|
recipients: await _helperRecipientsConvert(
|
|
|
|
recipientsArray,
|
|
|
|
recipientsAmtArray,
|
|
|
|
),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
return txnData.copyWith(
|
|
|
|
fee: Amount(
|
|
|
|
rawValue: feeForOneOutput,
|
|
|
|
fractionDigits: cryptoCurrency.fractionDigits,
|
|
|
|
),
|
|
|
|
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// no change output required
|
|
|
|
if (difference == feeForOneOutput) {
|
|
|
|
Logging.instance.log('1 output in tx', level: LogLevel.Info);
|
|
|
|
return await singleOutputTxn();
|
|
|
|
} else if (difference < feeForOneOutput) {
|
|
|
|
Logging.instance.log(
|
|
|
|
'Cannot pay tx fee - checking for more outputs and trying again',
|
|
|
|
level: LogLevel.Warning,
|
|
|
|
);
|
|
|
|
// try adding more outputs
|
|
|
|
if (spendableOutputs.length > inputsBeingConsumed) {
|
|
|
|
return coinSelection(
|
|
|
|
txData: txData,
|
|
|
|
isSendAll: isSendAll,
|
|
|
|
additionalOutputs: additionalOutputs + 1,
|
|
|
|
utxos: utxos,
|
|
|
|
coinControl: coinControl,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
throw Exception("Insufficient balance to pay transaction fee");
|
|
|
|
} else {
|
|
|
|
if (difference > (feeForOneOutput + cryptoCurrency.dustLimit.raw)) {
|
|
|
|
final changeOutputSize = difference - feeForTwoOutputs;
|
|
|
|
// check if possible to add the change output
|
|
|
|
if (changeOutputSize > cryptoCurrency.dustLimit.raw &&
|
|
|
|
difference - changeOutputSize == feeForTwoOutputs) {
|
2023-11-08 19:57:38 +00:00
|
|
|
// generate new change address if current change address has been used
|
|
|
|
await checkChangeAddressForTransactions();
|
|
|
|
final String newChangeAddress =
|
|
|
|
(await getCurrentChangeAddress())!.value;
|
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
BigInt feeBeingPaid = difference - changeOutputSize;
|
2023-11-08 19:57:38 +00:00
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
// add change output
|
2023-11-08 19:57:38 +00:00
|
|
|
recipientsArray.add(newChangeAddress);
|
|
|
|
recipientsAmtArray.add(changeOutputSize);
|
2024-06-04 21:07:31 +00:00
|
|
|
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance.log('2 outputs in tx', level: LogLevel.Info);
|
2024-06-04 21:07:31 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
'Input size: $satoshisBeingUsed',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
'Recipient output size: $satoshiAmountToSend',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
'Change Output Size: $changeOutputSize',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
'Difference (fee being paid): $feeBeingPaid sats',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2024-06-04 21:07:31 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
'Estimated fee: $feeForTwoOutputs',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
TxData txnData = await buildTransaction(
|
2023-11-08 19:57:38 +00:00
|
|
|
utxoSigningData: utxoSigningData,
|
|
|
|
txData: txData.copyWith(
|
2024-01-05 19:45:42 +00:00
|
|
|
recipients: await _helperRecipientsConvert(
|
2023-11-08 19:57:38 +00:00
|
|
|
recipientsArray,
|
|
|
|
recipientsAmtArray,
|
|
|
|
),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
// make sure minimum fee is accurate if that is being used
|
2024-06-04 21:07:31 +00:00
|
|
|
if (BigInt.from(txnData.vSize!) - feeBeingPaid == BigInt.one) {
|
|
|
|
final changeOutputSize = difference - BigInt.from(txnData.vSize!);
|
|
|
|
feeBeingPaid = difference - changeOutputSize;
|
2023-11-08 19:57:38 +00:00
|
|
|
recipientsAmtArray.removeLast();
|
|
|
|
recipientsAmtArray.add(changeOutputSize);
|
2024-06-04 21:07:31 +00:00
|
|
|
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
'Adjusted Input size: $satoshisBeingUsed',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
'Adjusted Recipient output size: $satoshiAmountToSend',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
Logging.instance.log(
|
|
|
|
'Adjusted Change Output Size: $changeOutputSize',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
'Adjusted Difference (fee being paid): $feeBeingPaid sats',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
'Adjusted Estimated fee: $feeForTwoOutputs',
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2024-06-04 21:07:31 +00:00
|
|
|
|
|
|
|
txnData = await buildTransaction(
|
2023-11-08 19:57:38 +00:00
|
|
|
utxoSigningData: utxoSigningData,
|
|
|
|
txData: txData.copyWith(
|
2024-01-05 19:45:42 +00:00
|
|
|
recipients: await _helperRecipientsConvert(
|
2023-11-08 19:57:38 +00:00
|
|
|
recipientsArray,
|
|
|
|
recipientsAmtArray,
|
|
|
|
),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
return txnData.copyWith(
|
2023-11-08 19:57:38 +00:00
|
|
|
fee: Amount(
|
2024-06-04 21:07:31 +00:00
|
|
|
rawValue: feeBeingPaid,
|
2023-11-08 19:57:38 +00:00
|
|
|
fractionDigits: cryptoCurrency.fractionDigits,
|
|
|
|
),
|
|
|
|
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
// Something went wrong here. It either overshot or undershot the estimated fee amount or the changeOutputSize
|
|
|
|
// is smaller than or equal to cryptoCurrency.dustLimit. Revert to single output transaction.
|
|
|
|
Logging.instance.log(
|
2024-06-04 21:07:31 +00:00
|
|
|
'Reverting to 1 output in tx',
|
2024-05-15 21:20:45 +00:00
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
|
2024-06-04 21:07:31 +00:00
|
|
|
return await singleOutputTxn();
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
}
|
2024-06-04 21:07:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return txData;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<TxData> _sendAllBuilder({
|
|
|
|
required TxData txData,
|
|
|
|
required String recipientAddress,
|
|
|
|
required BigInt satoshiAmountToSend,
|
|
|
|
required BigInt satoshisBeingUsed,
|
|
|
|
required List<SigningData> utxoSigningData,
|
|
|
|
required int? satsPerVByte,
|
|
|
|
required int feeRatePerKB,
|
|
|
|
}) async {
|
|
|
|
Logging.instance
|
|
|
|
.log("Attempting to send all $cryptoCurrency", level: LogLevel.Info);
|
|
|
|
if (txData.recipients!.length != 1) {
|
|
|
|
throw Exception(
|
|
|
|
"Send all to more than one recipient not yet supported",
|
2023-11-08 19:57:38 +00:00
|
|
|
);
|
2024-06-04 21:07:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
final int vSizeForOneOutput = (await buildTransaction(
|
|
|
|
utxoSigningData: utxoSigningData,
|
|
|
|
txData: txData.copyWith(
|
|
|
|
recipients: await _helperRecipientsConvert(
|
|
|
|
[recipientAddress],
|
|
|
|
[satoshisBeingUsed - BigInt.one],
|
2023-11-08 19:57:38 +00:00
|
|
|
),
|
2024-06-04 21:07:31 +00:00
|
|
|
),
|
|
|
|
))
|
|
|
|
.vSize!;
|
|
|
|
BigInt feeForOneOutput = BigInt.from(
|
|
|
|
satsPerVByte != null
|
|
|
|
? (satsPerVByte * vSizeForOneOutput)
|
|
|
|
: estimateTxFee(
|
|
|
|
vSize: vSizeForOneOutput,
|
|
|
|
feeRatePerKB: feeRatePerKB,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
if (satsPerVByte == null) {
|
|
|
|
final roughEstimate = roughFeeEstimate(
|
|
|
|
utxoSigningData.length,
|
|
|
|
1,
|
|
|
|
feeRatePerKB,
|
|
|
|
).raw;
|
|
|
|
if (feeForOneOutput < roughEstimate) {
|
|
|
|
feeForOneOutput = roughEstimate;
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
}
|
2024-06-04 21:07:31 +00:00
|
|
|
|
|
|
|
final amount = satoshiAmountToSend - feeForOneOutput;
|
|
|
|
|
|
|
|
if (amount.isNegative) {
|
|
|
|
throw Exception(
|
|
|
|
"Estimated fee ($feeForOneOutput sats) is greater than balance!",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
final data = await buildTransaction(
|
|
|
|
txData: txData.copyWith(
|
|
|
|
recipients: await _helperRecipientsConvert(
|
|
|
|
[recipientAddress],
|
|
|
|
[amount],
|
|
|
|
),
|
|
|
|
),
|
|
|
|
utxoSigningData: utxoSigningData,
|
|
|
|
);
|
|
|
|
|
|
|
|
return data.copyWith(
|
|
|
|
fee: Amount(
|
|
|
|
rawValue: feeForOneOutput,
|
|
|
|
fractionDigits: cryptoCurrency.fractionDigits,
|
|
|
|
),
|
|
|
|
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<List<SigningData>> fetchBuildTxData(
|
|
|
|
List<UTXO> utxosToUse,
|
|
|
|
) async {
|
|
|
|
// return data
|
2024-05-07 00:25:10 +00:00
|
|
|
final List<SigningData> signingData = [];
|
2023-11-08 19:57:38 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
// Populating the addresses to check
|
|
|
|
for (var i = 0; i < utxosToUse.length; i++) {
|
|
|
|
final derivePathType =
|
|
|
|
cryptoCurrency.addressType(address: utxosToUse[i].address!);
|
|
|
|
|
|
|
|
signingData.add(
|
|
|
|
SigningData(
|
|
|
|
derivePathType: derivePathType,
|
|
|
|
utxo: utxosToUse[i],
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
final root = await getRootHDNode();
|
|
|
|
|
|
|
|
for (final sd in signingData) {
|
|
|
|
coinlib.HDPrivateKey? keys;
|
|
|
|
final address = await mainDB.getAddress(walletId, sd.utxo.address!);
|
|
|
|
if (address?.derivationPath != null) {
|
|
|
|
if (address!.subType == AddressSubType.paynymReceive) {
|
2024-01-13 21:49:29 +00:00
|
|
|
if (this is PaynymInterface) {
|
|
|
|
final code = await (this as PaynymInterface)
|
|
|
|
.paymentCodeStringByKey(address.otherData!);
|
|
|
|
|
|
|
|
final bip47base =
|
|
|
|
await (this as PaynymInterface).getBip47BaseNode();
|
|
|
|
|
|
|
|
final privateKey = await (this as PaynymInterface)
|
|
|
|
.getPrivateKeyForPaynymReceivingAddress(
|
|
|
|
paymentCodeString: code!,
|
|
|
|
index: address.derivationIndex,
|
|
|
|
);
|
|
|
|
|
|
|
|
keys = coinlib.HDPrivateKey.fromKeyAndChainCode(
|
|
|
|
coinlib.ECPrivateKey.fromHex(privateKey.toHex),
|
|
|
|
bip47base.chainCode,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
throw Exception(
|
|
|
|
"$runtimeType tried to fetchBuildTxData for a paynym address"
|
|
|
|
" in a non PaynymInterface wallet",
|
|
|
|
);
|
|
|
|
}
|
2023-11-08 19:57:38 +00:00
|
|
|
} else {
|
|
|
|
keys = root.derivePath(address.derivationPath!.value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (keys == null) {
|
|
|
|
throw Exception(
|
2024-05-15 21:20:45 +00:00
|
|
|
"Failed to fetch signing data. Local db corrupt. Rescan wallet.",
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
2024-04-18 17:33:23 +00:00
|
|
|
sd.keyPair = keys;
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return signingData;
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance
|
|
|
|
.log("fetchBuildTxData() threw: $e,\n$s", level: LogLevel.Error);
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Builds and signs a transaction
|
2024-01-05 18:59:01 +00:00
|
|
|
Future<TxData> buildTransaction({
|
2023-11-08 19:57:38 +00:00
|
|
|
required TxData txData,
|
|
|
|
required List<SigningData> utxoSigningData,
|
2024-01-05 18:59:01 +00:00
|
|
|
}) async {
|
2023-11-08 19:57:38 +00:00
|
|
|
Logging.instance
|
|
|
|
.log("Starting buildTransaction ----------", level: LogLevel.Info);
|
|
|
|
|
2024-01-05 18:59:01 +00:00
|
|
|
// temp tx data to show in gui while waiting for real data from server
|
|
|
|
final List<InputV2> tempInputs = [];
|
|
|
|
final List<OutputV2> tempOutputs = [];
|
2023-11-08 19:57:38 +00:00
|
|
|
|
2024-04-15 21:48:55 +00:00
|
|
|
final List<coinlib.Output> prevOuts = [];
|
|
|
|
|
|
|
|
coinlib.Transaction clTx = coinlib.Transaction(
|
|
|
|
version: 1, // TODO: check if we can use 3 (as is default in coinlib)
|
|
|
|
inputs: [],
|
|
|
|
outputs: [],
|
|
|
|
);
|
|
|
|
|
2023-11-08 19:57:38 +00:00
|
|
|
// Add transaction inputs
|
|
|
|
for (var i = 0; i < utxoSigningData.length; i++) {
|
|
|
|
final txid = utxoSigningData[i].utxo.txid;
|
2024-04-15 21:48:55 +00:00
|
|
|
|
2024-04-18 17:33:23 +00:00
|
|
|
final hash = Uint8List.fromList(
|
|
|
|
txid.toUint8ListFromHex.reversed.toList(),
|
|
|
|
);
|
2024-04-15 21:48:55 +00:00
|
|
|
|
|
|
|
final prevOutpoint = coinlib.OutPoint(
|
|
|
|
hash,
|
2023-11-08 19:57:38 +00:00
|
|
|
utxoSigningData[i].utxo.vout,
|
|
|
|
);
|
2024-01-05 18:59:01 +00:00
|
|
|
|
2024-04-15 21:48:55 +00:00
|
|
|
final prevOutput = coinlib.Output.fromAddress(
|
|
|
|
BigInt.from(utxoSigningData[i].utxo.value),
|
|
|
|
coinlib.Address.fromString(
|
|
|
|
utxoSigningData[i].utxo.address!,
|
|
|
|
cryptoCurrency.networkParams,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
prevOuts.add(prevOutput);
|
|
|
|
|
|
|
|
final coinlib.Input input;
|
|
|
|
|
|
|
|
switch (utxoSigningData[i].derivePathType) {
|
|
|
|
case DerivePathType.bip44:
|
|
|
|
case DerivePathType.bch44:
|
|
|
|
input = coinlib.P2PKHInput(
|
|
|
|
prevOut: prevOutpoint,
|
2024-04-18 17:33:23 +00:00
|
|
|
publicKey: utxoSigningData[i].keyPair!.publicKey,
|
2024-04-15 21:48:55 +00:00
|
|
|
sequence: 0xffffffff - 1,
|
|
|
|
);
|
|
|
|
|
|
|
|
// TODO: fix this as it is (probably) wrong!
|
|
|
|
case DerivePathType.bip49:
|
2024-04-18 17:33:23 +00:00
|
|
|
throw Exception("TODO p2sh");
|
|
|
|
// input = coinlib.P2SHMultisigInput(
|
|
|
|
// prevOut: prevOutpoint,
|
|
|
|
// program: coinlib.MultisigProgram.decompile(
|
|
|
|
// utxoSigningData[i].redeemScript!,
|
|
|
|
// ),
|
|
|
|
// sequence: 0xffffffff - 1,
|
|
|
|
// );
|
2024-04-15 21:48:55 +00:00
|
|
|
|
|
|
|
case DerivePathType.bip84:
|
|
|
|
input = coinlib.P2WPKHInput(
|
|
|
|
prevOut: prevOutpoint,
|
2024-04-18 17:33:23 +00:00
|
|
|
publicKey: utxoSigningData[i].keyPair!.publicKey,
|
2024-04-15 21:48:55 +00:00
|
|
|
sequence: 0xffffffff - 1,
|
|
|
|
);
|
|
|
|
|
|
|
|
case DerivePathType.bip86:
|
|
|
|
input = coinlib.TaprootKeyInput(prevOut: prevOutpoint);
|
|
|
|
|
|
|
|
default:
|
|
|
|
throw UnsupportedError(
|
|
|
|
"Unknown derivation path type found: ${utxoSigningData[i].derivePathType}",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
clTx = clTx.addInput(input);
|
|
|
|
|
2024-01-05 18:59:01 +00:00
|
|
|
tempInputs.add(
|
|
|
|
InputV2.isarCantDoRequiredInDefaultConstructor(
|
2024-04-15 21:48:55 +00:00
|
|
|
scriptSigHex: input.scriptSig.toHex,
|
2024-01-14 17:26:04 +00:00
|
|
|
scriptSigAsm: null,
|
2024-01-05 18:59:01 +00:00
|
|
|
sequence: 0xffffffff - 1,
|
|
|
|
outpoint: OutpointV2.isarCantDoRequiredInDefaultConstructor(
|
|
|
|
txid: utxoSigningData[i].utxo.txid,
|
|
|
|
vout: utxoSigningData[i].utxo.vout,
|
|
|
|
),
|
|
|
|
addresses: utxoSigningData[i].utxo.address == null
|
|
|
|
? []
|
|
|
|
: [utxoSigningData[i].utxo.address!],
|
|
|
|
valueStringSats: utxoSigningData[i].utxo.value.toString(),
|
|
|
|
witness: null,
|
|
|
|
innerRedeemScriptAsm: null,
|
|
|
|
coinbase: null,
|
|
|
|
walletOwns: true,
|
|
|
|
),
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add transaction output
|
|
|
|
for (var i = 0; i < txData.recipients!.length; i++) {
|
2024-04-15 21:48:55 +00:00
|
|
|
final address = coinlib.Address.fromString(
|
2024-01-12 20:49:05 +00:00
|
|
|
normalizeAddress(txData.recipients![i].address),
|
2024-04-15 21:48:55 +00:00
|
|
|
cryptoCurrency.networkParams,
|
|
|
|
);
|
|
|
|
|
|
|
|
final output = coinlib.Output.fromAddress(
|
|
|
|
txData.recipients![i].amount.raw,
|
|
|
|
address,
|
2023-11-08 19:57:38 +00:00
|
|
|
);
|
2024-01-05 18:59:01 +00:00
|
|
|
|
2024-04-15 21:48:55 +00:00
|
|
|
clTx = clTx.addOutput(output);
|
|
|
|
|
2024-01-05 18:59:01 +00:00
|
|
|
tempOutputs.add(
|
|
|
|
OutputV2.isarCantDoRequiredInDefaultConstructor(
|
|
|
|
scriptPubKeyHex: "000000",
|
|
|
|
valueStringSats: txData.recipients![i].amount.raw.toString(),
|
|
|
|
addresses: [
|
|
|
|
txData.recipients![i].address.toString(),
|
|
|
|
],
|
|
|
|
walletOwns: (await mainDB.isar.addresses
|
|
|
|
.where()
|
|
|
|
.walletIdEqualTo(walletId)
|
|
|
|
.filter()
|
|
|
|
.valueEqualTo(txData.recipients![i].address)
|
|
|
|
.valueProperty()
|
|
|
|
.findFirst()) !=
|
|
|
|
null,
|
|
|
|
),
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
// Sign the transaction accordingly
|
|
|
|
for (var i = 0; i < utxoSigningData.length; i++) {
|
2024-04-15 21:48:55 +00:00
|
|
|
final value = BigInt.from(utxoSigningData[i].utxo.value);
|
2024-04-18 17:33:23 +00:00
|
|
|
coinlib.ECPrivateKey key = utxoSigningData[i].keyPair!.privateKey;
|
2024-04-15 21:48:55 +00:00
|
|
|
|
|
|
|
if (clTx.inputs[i] is coinlib.TaprootKeyInput) {
|
|
|
|
final taproot = coinlib.Taproot(
|
2024-04-18 17:33:23 +00:00
|
|
|
internalKey: utxoSigningData[i].keyPair!.publicKey,
|
2024-04-15 21:48:55 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
key = taproot.tweakPrivateKey(key);
|
|
|
|
}
|
|
|
|
|
|
|
|
clTx = clTx.sign(
|
|
|
|
inputN: i,
|
|
|
|
value: value,
|
|
|
|
key: key,
|
|
|
|
prevOuts: prevOuts,
|
2023-11-08 19:57:38 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
} catch (e, s) {
|
2024-05-15 21:20:45 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
"Caught exception while signing transaction: $e\n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
|
|
|
|
return txData.copyWith(
|
2024-04-15 21:48:55 +00:00
|
|
|
raw: clTx.toHex(),
|
2024-05-10 21:54:41 +00:00
|
|
|
// dirty shortcut for peercoin's weirdness
|
|
|
|
vSize: this is PeercoinWallet ? clTx.size : clTx.vSize(),
|
2024-01-05 18:59:01 +00:00
|
|
|
tempTx: TransactionV2(
|
|
|
|
walletId: walletId,
|
|
|
|
blockHash: null,
|
2024-04-15 21:48:55 +00:00
|
|
|
hash: clTx.hashHex,
|
|
|
|
txid: clTx.txid,
|
2024-01-05 18:59:01 +00:00
|
|
|
height: null,
|
|
|
|
timestamp: DateTime.timestamp().millisecondsSinceEpoch ~/ 1000,
|
|
|
|
inputs: List.unmodifiable(tempInputs),
|
|
|
|
outputs: List.unmodifiable(tempOutputs),
|
2024-04-15 21:48:55 +00:00
|
|
|
version: clTx.version,
|
2024-01-14 17:26:04 +00:00
|
|
|
type:
|
|
|
|
tempOutputs.map((e) => e.walletOwns).fold(true, (p, e) => p &= e) &&
|
|
|
|
txData.paynymAccountLite == null
|
|
|
|
? TransactionType.sentToSelf
|
|
|
|
: TransactionType.outgoing,
|
2024-01-05 18:59:01 +00:00
|
|
|
subType: TransactionSubType.none,
|
|
|
|
otherData: null,
|
|
|
|
),
|
2023-11-08 19:57:38 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-09-18 21:28:31 +00:00
|
|
|
Future<int> fetchChainHeight() async {
|
|
|
|
try {
|
2024-04-18 23:17:45 +00:00
|
|
|
return await ClientManager.sharedInstance.getChainHeightFor(
|
|
|
|
cryptoCurrency,
|
2024-02-17 08:47:53 +00:00
|
|
|
);
|
2024-02-16 06:32:06 +00:00
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
"Exception rethrown in fetchChainHeight\nError: $e\nStack trace: $s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
2024-02-16 06:32:06 +00:00
|
|
|
// completer.completeError(e, s);
|
|
|
|
// return Future.error(e, s);
|
2023-09-18 21:28:31 +00:00
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-06 23:10:07 +00:00
|
|
|
Future<int> fetchTxCount({required String addressScriptHash}) async {
|
|
|
|
final transactions =
|
2023-11-14 20:31:53 +00:00
|
|
|
await electrumXClient.getHistory(scripthash: addressScriptHash);
|
2023-11-06 23:10:07 +00:00
|
|
|
return transactions.length;
|
|
|
|
}
|
|
|
|
|
2024-02-22 05:16:53 +00:00
|
|
|
/// Should return a list of tx counts matching the list of addresses given
|
|
|
|
Future<List<int>> fetchTxCountBatched({
|
|
|
|
required List<String> addresses,
|
2023-11-07 18:19:42 +00:00
|
|
|
}) async {
|
|
|
|
try {
|
2024-02-22 05:16:53 +00:00
|
|
|
final response = await electrumXClient.getBatchHistory(
|
2024-05-15 21:20:45 +00:00
|
|
|
args: addresses
|
|
|
|
.map((e) => [cryptoCurrency.addressToScriptHash(address: e)])
|
|
|
|
.toList(growable: false),
|
|
|
|
);
|
2024-02-22 05:16:53 +00:00
|
|
|
|
|
|
|
final List<int> result = [];
|
|
|
|
for (final entry in response) {
|
|
|
|
result.add(entry.length);
|
2023-11-07 18:19:42 +00:00
|
|
|
}
|
|
|
|
return result;
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
"Exception rethrown in _getBatchTxCount(address: $addresses: $e\n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
2023-11-07 18:19:42 +00:00
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-18 23:47:06 +00:00
|
|
|
Future<ElectrumXNode> _getCurrentElectrumXNode() async {
|
2023-11-06 21:37:44 +00:00
|
|
|
final node = getCurrentNode();
|
2023-09-18 21:28:31 +00:00
|
|
|
|
|
|
|
return ElectrumXNode(
|
|
|
|
address: node.host,
|
|
|
|
port: node.port,
|
|
|
|
name: node.name,
|
|
|
|
useSSL: node.useSSL,
|
|
|
|
id: node.id,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-01-18 23:47:06 +00:00
|
|
|
Future<void> updateElectrumX() async {
|
2023-09-18 21:28:31 +00:00
|
|
|
final failovers = nodeService
|
2024-05-15 21:20:45 +00:00
|
|
|
.failoverNodesFor(currency: cryptoCurrency)
|
|
|
|
.map(
|
|
|
|
(e) => ElectrumXNode(
|
|
|
|
address: e.host,
|
|
|
|
port: e.port,
|
|
|
|
name: e.name,
|
|
|
|
id: e.id,
|
|
|
|
useSSL: e.useSSL,
|
|
|
|
),
|
|
|
|
)
|
2023-09-18 21:28:31 +00:00
|
|
|
.toList();
|
|
|
|
|
2024-01-18 23:47:06 +00:00
|
|
|
final newNode = await _getCurrentElectrumXNode();
|
2024-02-16 22:33:51 +00:00
|
|
|
try {
|
2024-04-18 23:17:45 +00:00
|
|
|
await electrumXClient.closeAdapter();
|
2024-04-15 16:31:57 +00:00
|
|
|
} catch (e) {
|
2024-02-16 22:33:51 +00:00
|
|
|
if (e.toString().contains("initialized")) {
|
|
|
|
// Ignore. This should happen every first time the wallet is opened.
|
|
|
|
} else {
|
|
|
|
Logging.instance
|
|
|
|
.log("Error closing electrumXClient: $e", level: LogLevel.Error);
|
|
|
|
}
|
|
|
|
}
|
2023-11-14 20:31:53 +00:00
|
|
|
electrumXClient = ElectrumXClient.from(
|
2023-09-18 21:28:31 +00:00
|
|
|
node: newNode,
|
|
|
|
prefs: prefs,
|
|
|
|
failovers: failovers,
|
2024-04-18 23:17:45 +00:00
|
|
|
cryptoCurrency: cryptoCurrency,
|
2023-09-18 21:28:31 +00:00
|
|
|
);
|
2023-11-14 20:31:53 +00:00
|
|
|
electrumXCachedClient = CachedElectrumXClient.from(
|
|
|
|
electrumXClient: electrumXClient,
|
2023-09-18 21:28:31 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
//============================================================================
|
|
|
|
|
2023-11-14 19:21:21 +00:00
|
|
|
Future<({List<Address> addresses, int index})> checkGapsBatched(
|
2023-11-07 18:19:42 +00:00
|
|
|
int txCountBatchSize,
|
|
|
|
coinlib.HDPrivateKey root,
|
|
|
|
DerivePathType type,
|
|
|
|
int chain,
|
|
|
|
) async {
|
2024-05-07 00:25:10 +00:00
|
|
|
final List<Address> addressArray = [];
|
2023-11-07 18:19:42 +00:00
|
|
|
int gapCounter = 0;
|
|
|
|
int highestIndexWithHistory = 0;
|
|
|
|
|
|
|
|
for (int index = 0;
|
|
|
|
index < cryptoCurrency.maxNumberOfIndexesToCheck &&
|
|
|
|
gapCounter < cryptoCurrency.maxUnusedAddressGap;
|
|
|
|
index += txCountBatchSize) {
|
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
"index: $index, \t GapCounter $chain ${type.name}: $gapCounter",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-07 18:19:42 +00:00
|
|
|
|
2024-05-07 00:25:10 +00:00
|
|
|
final List<String> txCountCallArgs = [];
|
2023-11-07 18:19:42 +00:00
|
|
|
|
|
|
|
for (int j = 0; j < txCountBatchSize; j++) {
|
|
|
|
final derivePath = cryptoCurrency.constructDerivePath(
|
|
|
|
derivePathType: type,
|
|
|
|
chain: chain,
|
|
|
|
index: index + j,
|
|
|
|
);
|
|
|
|
|
|
|
|
final keys = root.derivePath(derivePath);
|
|
|
|
|
|
|
|
final addressData = cryptoCurrency.getAddressForPublicKey(
|
|
|
|
publicKey: keys.publicKey,
|
|
|
|
derivePathType: type,
|
|
|
|
);
|
|
|
|
|
2023-11-14 20:01:47 +00:00
|
|
|
final addressString = convertAddressString(
|
|
|
|
addressData.address.toString(),
|
|
|
|
);
|
|
|
|
|
2023-11-07 18:19:42 +00:00
|
|
|
final address = Address(
|
|
|
|
walletId: walletId,
|
2023-11-14 20:01:47 +00:00
|
|
|
value: addressString,
|
2023-11-07 18:19:42 +00:00
|
|
|
publicKey: keys.publicKey.data,
|
|
|
|
type: addressData.addressType,
|
|
|
|
derivationIndex: index + j,
|
|
|
|
derivationPath: DerivationPath()..value = derivePath,
|
|
|
|
subType:
|
|
|
|
chain == 0 ? AddressSubType.receiving : AddressSubType.change,
|
|
|
|
);
|
|
|
|
|
|
|
|
addressArray.add(address);
|
|
|
|
|
2024-02-22 05:16:53 +00:00
|
|
|
txCountCallArgs.add(
|
|
|
|
addressString,
|
|
|
|
);
|
2023-11-07 18:19:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// get address tx counts
|
|
|
|
final counts = await fetchTxCountBatched(addresses: txCountCallArgs);
|
|
|
|
|
|
|
|
// check and add appropriate addresses
|
|
|
|
for (int k = 0; k < txCountBatchSize; k++) {
|
2024-02-22 05:16:53 +00:00
|
|
|
final count = counts[k];
|
2023-11-07 18:19:42 +00:00
|
|
|
|
|
|
|
if (count > 0) {
|
|
|
|
// update highest
|
|
|
|
highestIndexWithHistory = index + k;
|
|
|
|
|
|
|
|
// reset counter
|
|
|
|
gapCounter = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
// increase counter when no tx history found
|
|
|
|
if (count == 0) {
|
|
|
|
gapCounter++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// // cache all the transactions while waiting for the current function to finish.
|
|
|
|
// unawaited(getTransactionCacheEarly(addressArray));
|
|
|
|
}
|
|
|
|
return (index: highestIndexWithHistory, addresses: addressArray);
|
|
|
|
}
|
|
|
|
|
2023-11-14 19:21:21 +00:00
|
|
|
Future<({List<Address> addresses, int index})> checkGapsLinearly(
|
|
|
|
coinlib.HDPrivateKey root,
|
|
|
|
DerivePathType type,
|
|
|
|
int chain,
|
|
|
|
) async {
|
2024-05-07 00:25:10 +00:00
|
|
|
final List<Address> addressArray = [];
|
2023-11-14 19:21:21 +00:00
|
|
|
int gapCounter = 0;
|
|
|
|
int index = 0;
|
|
|
|
for (;
|
|
|
|
index < cryptoCurrency.maxNumberOfIndexesToCheck &&
|
|
|
|
gapCounter < cryptoCurrency.maxUnusedAddressGap;
|
|
|
|
index++) {
|
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
"index: $index, \t GapCounter chain=$chain ${type.name}: $gapCounter",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-14 19:21:21 +00:00
|
|
|
|
|
|
|
final derivePath = cryptoCurrency.constructDerivePath(
|
|
|
|
derivePathType: type,
|
|
|
|
chain: chain,
|
|
|
|
index: index,
|
|
|
|
);
|
|
|
|
final keys = root.derivePath(derivePath);
|
|
|
|
final addressData = cryptoCurrency.getAddressForPublicKey(
|
|
|
|
publicKey: keys.publicKey,
|
|
|
|
derivePathType: type,
|
|
|
|
);
|
|
|
|
|
2023-11-14 20:01:47 +00:00
|
|
|
final addressString = convertAddressString(
|
|
|
|
addressData.address.toString(),
|
|
|
|
);
|
2023-11-14 19:21:21 +00:00
|
|
|
|
|
|
|
final address = Address(
|
|
|
|
walletId: walletId,
|
|
|
|
value: addressString,
|
|
|
|
publicKey: keys.publicKey.data,
|
|
|
|
type: addressData.addressType,
|
|
|
|
derivationIndex: index,
|
|
|
|
derivationPath: DerivationPath()..value = derivePath,
|
|
|
|
subType: chain == 0 ? AddressSubType.receiving : AddressSubType.change,
|
|
|
|
);
|
|
|
|
|
|
|
|
// get address tx count
|
|
|
|
final count = await fetchTxCount(
|
|
|
|
addressScriptHash: cryptoCurrency.addressToScriptHash(
|
|
|
|
address: address.value,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
// check and add appropriate addresses
|
|
|
|
if (count > 0) {
|
|
|
|
// add address to array
|
|
|
|
addressArray.add(address);
|
|
|
|
// reset counter
|
|
|
|
gapCounter = 0;
|
|
|
|
// add info to derivations
|
|
|
|
} else {
|
|
|
|
// increase counter when no tx history found
|
|
|
|
gapCounter++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return (addresses: addressArray, index: index);
|
|
|
|
}
|
|
|
|
|
2023-10-30 22:58:15 +00:00
|
|
|
Future<List<Map<String, dynamic>>> fetchHistory(
|
|
|
|
Iterable<String> allAddresses,
|
2023-09-18 21:28:31 +00:00
|
|
|
) async {
|
|
|
|
try {
|
2024-05-07 00:25:10 +00:00
|
|
|
final List<Map<String, dynamic>> allTxHashes = [];
|
2023-09-18 21:28:31 +00:00
|
|
|
|
2024-05-07 00:25:31 +00:00
|
|
|
if (await serverCanBatch) {
|
2024-02-22 05:16:53 +00:00
|
|
|
final Map<int, List<List<dynamic>>> batches = {};
|
|
|
|
final Map<int, List<String>> batchIndexToAddressListMap = {};
|
2023-11-14 19:21:21 +00:00
|
|
|
const batchSizeMax = 100;
|
|
|
|
int batchNumber = 0;
|
|
|
|
for (int i = 0; i < allAddresses.length; i++) {
|
2024-02-22 05:16:53 +00:00
|
|
|
batches[batchNumber] ??= [];
|
|
|
|
batchIndexToAddressListMap[batchNumber] ??= [];
|
|
|
|
|
|
|
|
final address = allAddresses.elementAt(i);
|
2023-11-14 19:21:21 +00:00
|
|
|
final scriptHash = cryptoCurrency.addressToScriptHash(
|
2024-02-22 05:16:53 +00:00
|
|
|
address: address,
|
2023-11-14 19:21:21 +00:00
|
|
|
);
|
2024-02-22 05:16:53 +00:00
|
|
|
batches[batchNumber]!.add([scriptHash]);
|
|
|
|
batchIndexToAddressListMap[batchNumber]!.add(address);
|
2023-11-14 19:21:21 +00:00
|
|
|
if (i % batchSizeMax == batchSizeMax - 1) {
|
|
|
|
batchNumber++;
|
|
|
|
}
|
2023-09-18 21:28:31 +00:00
|
|
|
}
|
2023-11-14 19:21:21 +00:00
|
|
|
|
|
|
|
for (int i = 0; i < batches.length; i++) {
|
2023-11-14 20:31:53 +00:00
|
|
|
final response =
|
|
|
|
await electrumXClient.getBatchHistory(args: batches[i]!);
|
2024-02-22 05:16:53 +00:00
|
|
|
for (int j = 0; j < response.length; j++) {
|
|
|
|
final entry = response[j];
|
|
|
|
for (int k = 0; k < entry.length; k++) {
|
|
|
|
entry[k]["address"] = batchIndexToAddressListMap[i]![j];
|
|
|
|
// if (!allTxHashes.contains(entry[j])) {
|
|
|
|
allTxHashes.add(entry[k]);
|
|
|
|
// }
|
2023-11-14 19:21:21 +00:00
|
|
|
}
|
|
|
|
}
|
2023-09-18 21:28:31 +00:00
|
|
|
}
|
2023-11-14 19:21:21 +00:00
|
|
|
} else {
|
|
|
|
for (int i = 0; i < allAddresses.length; i++) {
|
2024-01-11 19:51:27 +00:00
|
|
|
final addressString = allAddresses.elementAt(i);
|
2023-11-14 19:21:21 +00:00
|
|
|
final scriptHash = cryptoCurrency.addressToScriptHash(
|
2024-01-11 19:51:27 +00:00
|
|
|
address: addressString,
|
2023-11-14 19:21:21 +00:00
|
|
|
);
|
|
|
|
|
2023-11-14 20:31:53 +00:00
|
|
|
final response = await electrumXClient.getHistory(
|
2023-11-14 19:21:21 +00:00
|
|
|
scripthash: scriptHash,
|
|
|
|
);
|
2023-09-18 21:28:31 +00:00
|
|
|
|
2023-11-14 19:21:21 +00:00
|
|
|
for (int j = 0; j < response.length; j++) {
|
2024-01-11 19:51:27 +00:00
|
|
|
response[j]["address"] = addressString;
|
2023-11-14 19:21:21 +00:00
|
|
|
if (!allTxHashes.contains(response[j])) {
|
|
|
|
allTxHashes.add(response[j]);
|
2023-09-18 21:28:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return allTxHashes;
|
|
|
|
} catch (e, s) {
|
2024-05-07 16:52:33 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
"$runtimeType._fetchHistory: $e\n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
2023-09-18 21:28:31 +00:00
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-06 23:10:07 +00:00
|
|
|
/// The optional (nullable) param [checkBlock] is a callback that can be used
|
|
|
|
/// to check if a utxo should be marked as blocked
|
2023-10-30 22:58:15 +00:00
|
|
|
Future<UTXO> parseUTXO({
|
|
|
|
required Map<String, dynamic> jsonUTXO,
|
|
|
|
}) async {
|
2023-11-14 20:31:53 +00:00
|
|
|
final txn = await electrumXCachedClient.getTransaction(
|
2023-10-30 22:58:15 +00:00
|
|
|
txHash: jsonUTXO["tx_hash"] as String,
|
|
|
|
verbose: true,
|
2024-05-15 21:20:45 +00:00
|
|
|
cryptoCurrency: cryptoCurrency,
|
2023-10-30 22:58:15 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
final vout = jsonUTXO["tx_pos"] as int;
|
|
|
|
|
|
|
|
final outputs = txn["vout"] as List;
|
|
|
|
|
|
|
|
String? scriptPubKey;
|
|
|
|
String? utxoOwnerAddress;
|
|
|
|
// get UTXO owner address
|
|
|
|
for (final output in outputs) {
|
|
|
|
if (output["n"] == vout) {
|
|
|
|
scriptPubKey = output["scriptPubKey"]?["hex"] as String?;
|
|
|
|
utxoOwnerAddress =
|
|
|
|
output["scriptPubKey"]?["addresses"]?[0] as String? ??
|
|
|
|
output["scriptPubKey"]?["address"] as String?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-05 00:37:46 +00:00
|
|
|
final checkBlockResult = await checkBlockUTXO(
|
|
|
|
jsonUTXO,
|
|
|
|
scriptPubKey,
|
|
|
|
txn,
|
|
|
|
utxoOwnerAddress,
|
|
|
|
);
|
2023-10-30 22:58:15 +00:00
|
|
|
|
|
|
|
final utxo = UTXO(
|
|
|
|
walletId: walletId,
|
|
|
|
txid: txn["txid"] as String,
|
|
|
|
vout: vout,
|
|
|
|
value: jsonUTXO["value"] as int,
|
2024-01-05 00:37:46 +00:00
|
|
|
name: checkBlockResult.utxoLabel ?? "",
|
2023-11-06 23:10:07 +00:00
|
|
|
isBlocked: checkBlockResult.blocked,
|
|
|
|
blockedReason: checkBlockResult.blockedReason,
|
2023-10-30 22:58:15 +00:00
|
|
|
isCoinbase: txn["is_coinbase"] as bool? ?? false,
|
|
|
|
blockHash: txn["blockhash"] as String?,
|
|
|
|
blockHeight: jsonUTXO["height"] as int?,
|
|
|
|
blockTime: txn["blocktime"] as int?,
|
|
|
|
address: utxoOwnerAddress,
|
|
|
|
);
|
|
|
|
|
|
|
|
return utxo;
|
|
|
|
}
|
|
|
|
|
2023-09-18 21:28:31 +00:00
|
|
|
//============================================================================
|
|
|
|
|
2023-11-06 23:10:07 +00:00
|
|
|
@override
|
|
|
|
Future<void> updateChainHeight() async {
|
|
|
|
final height = await fetchChainHeight();
|
|
|
|
await info.updateCachedChainHeight(
|
|
|
|
newHeight: height,
|
|
|
|
isar: mainDB.isar,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<bool> pingCheck() async {
|
|
|
|
try {
|
2023-11-14 20:31:53 +00:00
|
|
|
final result = await electrumXClient.ping();
|
2023-11-06 23:10:07 +00:00
|
|
|
return result;
|
|
|
|
} catch (_) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-18 21:28:31 +00:00
|
|
|
@override
|
|
|
|
Future<void> updateNode() async {
|
2024-01-18 23:47:06 +00:00
|
|
|
await updateElectrumX();
|
2023-09-18 21:28:31 +00:00
|
|
|
}
|
2023-11-03 19:46:55 +00:00
|
|
|
|
|
|
|
FeeObject? _cachedFees;
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<FeeObject> get fees async {
|
|
|
|
try {
|
|
|
|
const int f = 1, m = 5, s = 20;
|
|
|
|
|
2023-11-14 20:31:53 +00:00
|
|
|
final fast = await electrumXClient.estimateFee(blocks: f);
|
|
|
|
final medium = await electrumXClient.estimateFee(blocks: m);
|
|
|
|
final slow = await electrumXClient.estimateFee(blocks: s);
|
2023-11-03 19:46:55 +00:00
|
|
|
|
|
|
|
final feeObject = FeeObject(
|
|
|
|
numberOfBlocksFast: f,
|
|
|
|
numberOfBlocksAverage: m,
|
|
|
|
numberOfBlocksSlow: s,
|
|
|
|
fast: Amount.fromDecimal(
|
|
|
|
fast,
|
2024-05-15 21:20:45 +00:00
|
|
|
fractionDigits: info.coin.fractionDigits,
|
2023-11-03 19:46:55 +00:00
|
|
|
).raw.toInt(),
|
|
|
|
medium: Amount.fromDecimal(
|
|
|
|
medium,
|
2024-05-15 21:20:45 +00:00
|
|
|
fractionDigits: info.coin.fractionDigits,
|
2023-11-03 19:46:55 +00:00
|
|
|
).raw.toInt(),
|
|
|
|
slow: Amount.fromDecimal(
|
|
|
|
slow,
|
2024-05-15 21:20:45 +00:00
|
|
|
fractionDigits: info.coin.fractionDigits,
|
2023-11-03 19:46:55 +00:00
|
|
|
).raw.toInt(),
|
|
|
|
);
|
|
|
|
|
|
|
|
Logging.instance.log("fetched fees: $feeObject", level: LogLevel.Info);
|
|
|
|
_cachedFees = feeObject;
|
|
|
|
return _cachedFees!;
|
2024-02-06 04:40:39 +00:00
|
|
|
} catch (e, s) {
|
2023-11-03 19:46:55 +00:00
|
|
|
Logging.instance.log(
|
2024-02-06 04:40:39 +00:00
|
|
|
"Exception rethrown from _getFees(): $e\nStack trace: $s",
|
2023-11-03 19:46:55 +00:00
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
|
|
|
if (_cachedFees == null) {
|
|
|
|
rethrow;
|
|
|
|
} else {
|
|
|
|
return _cachedFees!;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<Amount> estimateFeeFor(Amount amount, int feeRate) async {
|
|
|
|
final available = info.cachedBalance.spendable;
|
|
|
|
final utxos = _spendableUTXOs(await mainDB.getUTXOs(walletId).findAll());
|
|
|
|
|
|
|
|
if (available == amount) {
|
|
|
|
return amount - (await _sweepAllEstimate(feeRate, utxos));
|
|
|
|
} else if (amount <= Amount.zero || amount > available) {
|
|
|
|
return roughFeeEstimate(1, 2, feeRate);
|
|
|
|
}
|
|
|
|
|
|
|
|
Amount runningBalance = Amount(
|
|
|
|
rawValue: BigInt.zero,
|
2024-05-15 21:20:45 +00:00
|
|
|
fractionDigits: info.coin.fractionDigits,
|
2023-11-03 19:46:55 +00:00
|
|
|
);
|
|
|
|
int inputCount = 0;
|
|
|
|
for (final output in utxos) {
|
|
|
|
if (!output.isBlocked) {
|
|
|
|
runningBalance += Amount(
|
|
|
|
rawValue: BigInt.from(output.value),
|
2024-05-15 21:20:45 +00:00
|
|
|
fractionDigits: info.coin.fractionDigits,
|
2023-11-03 19:46:55 +00:00
|
|
|
);
|
|
|
|
inputCount++;
|
|
|
|
if (runningBalance > amount) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
final oneOutPutFee = roughFeeEstimate(inputCount, 1, feeRate);
|
|
|
|
final twoOutPutFee = roughFeeEstimate(inputCount, 2, feeRate);
|
|
|
|
|
|
|
|
if (runningBalance - amount > oneOutPutFee) {
|
|
|
|
if (runningBalance - amount > oneOutPutFee + cryptoCurrency.dustLimit) {
|
|
|
|
final change = runningBalance - amount - twoOutPutFee;
|
|
|
|
if (change > cryptoCurrency.dustLimit &&
|
|
|
|
runningBalance - amount - change == twoOutPutFee) {
|
|
|
|
return runningBalance - amount - change;
|
|
|
|
} else {
|
|
|
|
return runningBalance - amount;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return runningBalance - amount;
|
|
|
|
}
|
|
|
|
} else if (runningBalance - amount == oneOutPutFee) {
|
|
|
|
return oneOutPutFee;
|
|
|
|
} else {
|
|
|
|
return twoOutPutFee;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-06 23:10:07 +00:00
|
|
|
@override
|
|
|
|
Future<void> checkReceivingAddressForTransactions() async {
|
|
|
|
try {
|
|
|
|
final currentReceiving = await getCurrentReceivingAddress();
|
|
|
|
|
|
|
|
final bool needsGenerate;
|
|
|
|
if (currentReceiving == null) {
|
|
|
|
// no addresses in db yet for some reason.
|
|
|
|
// Should not happen at this point...
|
|
|
|
|
|
|
|
needsGenerate = true;
|
|
|
|
} else {
|
|
|
|
final txCount = await fetchTxCount(
|
2023-11-08 19:57:38 +00:00
|
|
|
addressScriptHash: cryptoCurrency.addressToScriptHash(
|
|
|
|
address: currentReceiving.value,
|
|
|
|
),
|
2023-11-06 23:10:07 +00:00
|
|
|
);
|
|
|
|
needsGenerate = txCount > 0 || currentReceiving.derivationIndex < 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (needsGenerate) {
|
|
|
|
await generateNewReceivingAddress();
|
|
|
|
|
|
|
|
// TODO: get rid of this? Could cause problems (long loading/infinite loop or something)
|
|
|
|
// keep checking until address with no tx history is set as current
|
|
|
|
await checkReceivingAddressForTransactions();
|
|
|
|
}
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Exception rethrown from _checkReceivingAddressForTransactions"
|
|
|
|
"($cryptoCurrency): $e\n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-07 16:25:04 +00:00
|
|
|
@override
|
|
|
|
Future<void> checkChangeAddressForTransactions() async {
|
|
|
|
try {
|
|
|
|
final currentChange = await getCurrentChangeAddress();
|
|
|
|
|
|
|
|
final bool needsGenerate;
|
|
|
|
if (currentChange == null) {
|
|
|
|
// no addresses in db yet for some reason.
|
|
|
|
// Should not happen at this point...
|
|
|
|
|
|
|
|
needsGenerate = true;
|
|
|
|
} else {
|
|
|
|
final txCount = await fetchTxCount(
|
2023-11-08 19:57:38 +00:00
|
|
|
addressScriptHash: cryptoCurrency.addressToScriptHash(
|
|
|
|
address: currentChange.value,
|
|
|
|
),
|
2023-11-07 16:25:04 +00:00
|
|
|
);
|
|
|
|
needsGenerate = txCount > 0 || currentChange.derivationIndex < 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (needsGenerate) {
|
|
|
|
await generateNewChangeAddress();
|
|
|
|
|
|
|
|
// TODO: get rid of this? Could cause problems (long loading/infinite loop or something)
|
|
|
|
// keep checking until address with no tx history is set as current
|
|
|
|
await checkChangeAddressForTransactions();
|
|
|
|
}
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
2023-11-08 19:57:38 +00:00
|
|
|
"Exception rethrown from _checkChangeAddressForTransactions"
|
2023-11-07 18:19:42 +00:00
|
|
|
"($cryptoCurrency): $e\n$s",
|
2023-11-07 16:25:04 +00:00
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-07 18:19:42 +00:00
|
|
|
@override
|
|
|
|
Future<void> recover({required bool isRescan}) async {
|
|
|
|
final root = await getRootHDNode();
|
|
|
|
|
|
|
|
final List<Future<({int index, List<Address> addresses})>> receiveFutures =
|
|
|
|
[];
|
|
|
|
final List<Future<({int index, List<Address> addresses})>> changeFutures =
|
|
|
|
[];
|
|
|
|
|
|
|
|
const receiveChain = 0;
|
|
|
|
const changeChain = 1;
|
|
|
|
|
|
|
|
const txCountBatchSize = 12;
|
|
|
|
|
|
|
|
try {
|
|
|
|
await refreshMutex.protect(() async {
|
|
|
|
if (isRescan) {
|
|
|
|
// clear cache
|
2023-11-14 20:31:53 +00:00
|
|
|
await electrumXCachedClient.clearSharedTransactionCache(
|
2024-05-15 21:20:45 +00:00
|
|
|
cryptoCurrency: info.coin,
|
|
|
|
);
|
2023-11-07 18:19:42 +00:00
|
|
|
// clear blockchain info
|
|
|
|
await mainDB.deleteWalletBlockchainData(walletId);
|
|
|
|
}
|
|
|
|
|
|
|
|
// receiving addresses
|
|
|
|
Logging.instance.log(
|
|
|
|
"checking receiving addresses...",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
|
2024-05-07 00:25:31 +00:00
|
|
|
final canBatch = await serverCanBatch;
|
|
|
|
|
2023-11-07 18:19:42 +00:00
|
|
|
for (final type in cryptoCurrency.supportedDerivationPathTypes) {
|
|
|
|
receiveFutures.add(
|
2024-05-07 00:25:31 +00:00
|
|
|
canBatch
|
2023-11-14 19:21:21 +00:00
|
|
|
? checkGapsBatched(
|
|
|
|
txCountBatchSize,
|
|
|
|
root,
|
|
|
|
type,
|
|
|
|
receiveChain,
|
|
|
|
)
|
|
|
|
: checkGapsLinearly(
|
|
|
|
root,
|
|
|
|
type,
|
|
|
|
receiveChain,
|
|
|
|
),
|
2023-11-07 18:19:42 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// change addresses
|
|
|
|
Logging.instance.log(
|
|
|
|
"checking change addresses...",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
for (final type in cryptoCurrency.supportedDerivationPathTypes) {
|
|
|
|
changeFutures.add(
|
2024-05-07 00:25:31 +00:00
|
|
|
canBatch
|
2023-11-14 19:21:21 +00:00
|
|
|
? checkGapsBatched(
|
|
|
|
txCountBatchSize,
|
|
|
|
root,
|
|
|
|
type,
|
|
|
|
changeChain,
|
|
|
|
)
|
|
|
|
: checkGapsLinearly(
|
|
|
|
root,
|
|
|
|
type,
|
|
|
|
changeChain,
|
|
|
|
),
|
2023-11-07 18:19:42 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// io limitations may require running these linearly instead
|
|
|
|
final futuresResult = await Future.wait([
|
|
|
|
Future.wait(receiveFutures),
|
|
|
|
Future.wait(changeFutures),
|
|
|
|
]);
|
|
|
|
|
|
|
|
final receiveResults = futuresResult[0];
|
|
|
|
final changeResults = futuresResult[1];
|
|
|
|
|
|
|
|
final List<Address> addressesToStore = [];
|
|
|
|
|
|
|
|
int highestReceivingIndexWithHistory = 0;
|
|
|
|
|
|
|
|
for (final tuple in receiveResults) {
|
|
|
|
if (tuple.addresses.isEmpty) {
|
|
|
|
await checkReceivingAddressForTransactions();
|
|
|
|
} else {
|
|
|
|
highestReceivingIndexWithHistory = max(
|
|
|
|
tuple.index,
|
|
|
|
highestReceivingIndexWithHistory,
|
|
|
|
);
|
|
|
|
addressesToStore.addAll(tuple.addresses);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int highestChangeIndexWithHistory = 0;
|
|
|
|
// If restoring a wallet that never sent any funds with change, then set changeArray
|
|
|
|
// manually. If we didn't do this, it'd store an empty array.
|
|
|
|
for (final tuple in changeResults) {
|
|
|
|
if (tuple.addresses.isEmpty) {
|
|
|
|
await checkChangeAddressForTransactions();
|
|
|
|
} else {
|
|
|
|
highestChangeIndexWithHistory = max(
|
|
|
|
tuple.index,
|
|
|
|
highestChangeIndexWithHistory,
|
|
|
|
);
|
|
|
|
addressesToStore.addAll(tuple.addresses);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// remove extra addresses to help minimize risk of creating a large gap
|
2024-05-15 21:20:45 +00:00
|
|
|
addressesToStore.removeWhere(
|
|
|
|
(e) =>
|
|
|
|
e.subType == AddressSubType.change &&
|
|
|
|
e.derivationIndex > highestChangeIndexWithHistory,
|
|
|
|
);
|
|
|
|
addressesToStore.removeWhere(
|
|
|
|
(e) =>
|
|
|
|
e.subType == AddressSubType.receiving &&
|
|
|
|
e.derivationIndex > highestReceivingIndexWithHistory,
|
|
|
|
);
|
2023-11-07 18:19:42 +00:00
|
|
|
|
|
|
|
await mainDB.updateOrPutAddresses(addressesToStore);
|
2024-01-14 19:03:07 +00:00
|
|
|
|
|
|
|
if (this is PaynymInterface) {
|
|
|
|
final notificationAddress =
|
|
|
|
await (this as PaynymInterface).getMyNotificationAddress();
|
|
|
|
|
|
|
|
await (this as BitcoinWallet)
|
|
|
|
.updateTransactions(overrideAddresses: [notificationAddress]);
|
|
|
|
|
|
|
|
// get own payment code
|
|
|
|
// isSegwit does not matter here at all
|
|
|
|
final myCode =
|
|
|
|
await (this as PaynymInterface).getPaymentCode(isSegwit: false);
|
|
|
|
|
|
|
|
try {
|
|
|
|
final Set<String> codesToCheck = {};
|
|
|
|
final nym = await PaynymIsApi().nym(myCode.toString());
|
|
|
|
if (nym.value != null) {
|
|
|
|
for (final follower in nym.value!.followers) {
|
|
|
|
codesToCheck.add(follower.code);
|
|
|
|
}
|
|
|
|
for (final following in nym.value!.following) {
|
|
|
|
codesToCheck.add(following.code);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// restore paynym transactions
|
|
|
|
await (this as PaynymInterface).restoreAllHistory(
|
|
|
|
maxUnusedAddressGap: 20,
|
|
|
|
maxNumberOfIndexesToCheck: 10000,
|
|
|
|
paymentCodeStrings: codesToCheck,
|
|
|
|
);
|
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Failed to check paynym.is followers/following for history during "
|
|
|
|
"bitcoin wallet ($walletId ${info.name}) "
|
|
|
|
"_recoverWalletFromBIP32SeedPhrase: $e/n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2023-11-07 18:19:42 +00:00
|
|
|
});
|
|
|
|
|
2024-01-14 19:03:07 +00:00
|
|
|
unawaited(refresh());
|
2023-11-07 18:19:42 +00:00
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
2024-05-15 21:20:45 +00:00
|
|
|
"Exception rethrown from electrumx_mixin recover(): $e\n$s",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
2023-11-07 18:19:42 +00:00
|
|
|
|
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-06 23:10:07 +00:00
|
|
|
@override
|
2024-01-05 00:37:46 +00:00
|
|
|
Future<bool> updateUTXOs() async {
|
2023-11-29 15:53:30 +00:00
|
|
|
final allAddresses = await fetchAddressesForElectrumXScan();
|
2023-11-06 23:10:07 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
final fetchedUtxoList = <List<Map<String, dynamic>>>[];
|
|
|
|
|
2024-05-07 00:25:31 +00:00
|
|
|
if (await serverCanBatch) {
|
2024-02-22 05:16:53 +00:00
|
|
|
final Map<int, List<List<dynamic>>> batchArgs = {};
|
2023-11-14 19:21:21 +00:00
|
|
|
const batchSizeMax = 10;
|
|
|
|
int batchNumber = 0;
|
|
|
|
for (int i = 0; i < allAddresses.length; i++) {
|
2024-02-22 05:16:53 +00:00
|
|
|
batchArgs[batchNumber] ??= [];
|
2023-11-14 19:21:21 +00:00
|
|
|
final scriptHash = cryptoCurrency.addressToScriptHash(
|
|
|
|
address: allAddresses[i].value,
|
|
|
|
);
|
|
|
|
|
2024-02-22 05:16:53 +00:00
|
|
|
batchArgs[batchNumber]!.add([scriptHash]);
|
2023-11-14 19:21:21 +00:00
|
|
|
if (i % batchSizeMax == batchSizeMax - 1) {
|
|
|
|
batchNumber++;
|
|
|
|
}
|
2023-11-06 23:10:07 +00:00
|
|
|
}
|
|
|
|
|
2024-02-22 05:16:53 +00:00
|
|
|
for (int i = 0; i < batchArgs.length; i++) {
|
2023-11-14 20:31:53 +00:00
|
|
|
final response =
|
2024-02-22 05:16:53 +00:00
|
|
|
await electrumXClient.getBatchUTXOs(args: batchArgs[i]!);
|
|
|
|
for (final entry in response) {
|
|
|
|
if (entry.isNotEmpty) {
|
|
|
|
fetchedUtxoList.add(entry);
|
2023-11-14 19:21:21 +00:00
|
|
|
}
|
|
|
|
}
|
2023-11-06 23:10:07 +00:00
|
|
|
}
|
2023-11-14 19:21:21 +00:00
|
|
|
} else {
|
|
|
|
for (int i = 0; i < allAddresses.length; i++) {
|
|
|
|
final scriptHash = cryptoCurrency.addressToScriptHash(
|
|
|
|
address: allAddresses[i].value,
|
|
|
|
);
|
2023-11-06 23:10:07 +00:00
|
|
|
|
2023-11-14 20:31:53 +00:00
|
|
|
final utxos = await electrumXClient.getUTXOs(scripthash: scriptHash);
|
2023-11-14 19:21:21 +00:00
|
|
|
if (utxos.isNotEmpty) {
|
|
|
|
fetchedUtxoList.add(utxos);
|
2023-11-06 23:10:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
final List<UTXO> outputArray = [];
|
|
|
|
|
|
|
|
for (int i = 0; i < fetchedUtxoList.length; i++) {
|
|
|
|
for (int j = 0; j < fetchedUtxoList[i].length; j++) {
|
|
|
|
final utxo = await parseUTXO(
|
|
|
|
jsonUTXO: fetchedUtxoList[i][j],
|
|
|
|
);
|
|
|
|
|
|
|
|
outputArray.add(utxo);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-05 00:37:46 +00:00
|
|
|
return await mainDB.updateUTXOs(walletId, outputArray);
|
2023-11-06 23:10:07 +00:00
|
|
|
} catch (e, s) {
|
|
|
|
Logging.instance.log(
|
|
|
|
"Output fetch unsuccessful: $e\n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
2024-01-05 00:37:46 +00:00
|
|
|
return false;
|
2023-11-06 23:10:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-08 19:57:38 +00:00
|
|
|
@override
|
|
|
|
Future<TxData> confirmSend({required TxData txData}) async {
|
|
|
|
try {
|
|
|
|
Logging.instance.log("confirmSend txData: $txData", level: LogLevel.Info);
|
|
|
|
|
2023-11-14 20:31:53 +00:00
|
|
|
final txHash = await electrumXClient.broadcastTransaction(
|
2023-11-08 19:57:38 +00:00
|
|
|
rawTx: txData.raw!,
|
|
|
|
);
|
|
|
|
Logging.instance.log("Sent txHash: $txHash", level: LogLevel.Info);
|
|
|
|
|
|
|
|
txData = txData.copyWith(
|
|
|
|
usedUTXOs:
|
|
|
|
txData.usedUTXOs!.map((e) => e.copyWith(used: true)).toList(),
|
|
|
|
|
|
|
|
// TODO revisit setting these both
|
|
|
|
txHash: txHash,
|
|
|
|
txid: txHash,
|
|
|
|
);
|
|
|
|
// mark utxos as used
|
|
|
|
await mainDB.putUTXOs(txData.usedUTXOs!);
|
|
|
|
|
2024-01-05 18:59:01 +00:00
|
|
|
return await updateSentCachedTxData(txData: txData);
|
2023-11-08 19:57:38 +00:00
|
|
|
} catch (e, s) {
|
2024-05-15 21:20:45 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
"Exception rethrown from confirmSend(): $e\n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<TxData> prepareSend({required TxData txData}) async {
|
|
|
|
try {
|
|
|
|
final feeRateType = txData.feeRateType;
|
|
|
|
final customSatsPerVByte = txData.satsPerVByte;
|
|
|
|
final feeRateAmount = txData.feeRateAmount;
|
|
|
|
final utxos = txData.utxos;
|
|
|
|
|
|
|
|
if (customSatsPerVByte != null) {
|
|
|
|
// check for send all
|
|
|
|
bool isSendAll = false;
|
|
|
|
if (txData.amount == info.cachedBalance.spendable) {
|
|
|
|
isSendAll = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
final bool coinControl = utxos != null;
|
|
|
|
|
|
|
|
final result = await coinSelection(
|
|
|
|
txData: txData.copyWith(feeRateAmount: -1),
|
|
|
|
isSendAll: isSendAll,
|
|
|
|
utxos: utxos?.toList(),
|
|
|
|
coinControl: coinControl,
|
|
|
|
);
|
|
|
|
|
|
|
|
Logging.instance
|
|
|
|
.log("PREPARE SEND RESULT: $result", level: LogLevel.Info);
|
|
|
|
|
2024-01-15 19:45:50 +00:00
|
|
|
if (result.fee!.raw.toInt() < result.vSize!) {
|
2023-11-08 19:57:38 +00:00
|
|
|
throw Exception(
|
2024-05-15 21:20:45 +00:00
|
|
|
"Error in fee calculation: Transaction fee cannot be less than vSize",
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
} else if (feeRateType is FeeRateType || feeRateAmount is int) {
|
|
|
|
late final int rate;
|
|
|
|
if (feeRateType is FeeRateType) {
|
|
|
|
int fee = 0;
|
|
|
|
final feeObject = await fees;
|
|
|
|
switch (feeRateType) {
|
|
|
|
case FeeRateType.fast:
|
|
|
|
fee = feeObject.fast;
|
|
|
|
break;
|
|
|
|
case FeeRateType.average:
|
|
|
|
fee = feeObject.medium;
|
|
|
|
break;
|
|
|
|
case FeeRateType.slow:
|
|
|
|
fee = feeObject.slow;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
throw ArgumentError("Invalid use of custom fee");
|
|
|
|
}
|
|
|
|
rate = fee;
|
|
|
|
} else {
|
|
|
|
rate = feeRateAmount as int;
|
|
|
|
}
|
|
|
|
|
|
|
|
// check for send all
|
|
|
|
bool isSendAll = false;
|
|
|
|
if (txData.amount == info.cachedBalance.spendable) {
|
|
|
|
isSendAll = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
final bool coinControl = utxos != null;
|
|
|
|
|
|
|
|
final result = await coinSelection(
|
|
|
|
txData: txData.copyWith(
|
|
|
|
feeRateAmount: rate,
|
|
|
|
),
|
|
|
|
isSendAll: isSendAll,
|
|
|
|
utxos: utxos?.toList(),
|
|
|
|
coinControl: coinControl,
|
|
|
|
);
|
|
|
|
|
|
|
|
Logging.instance.log("prepare send: $result", level: LogLevel.Info);
|
2023-11-09 21:31:23 +00:00
|
|
|
if (result.fee!.raw.toInt() < result.vSize!) {
|
2023-11-08 19:57:38 +00:00
|
|
|
throw Exception(
|
2024-02-20 18:33:29 +00:00
|
|
|
"Error in fee calculation: Transaction fee (${result.fee!.raw.toInt()}) cannot "
|
|
|
|
"be less than vSize (${result.vSize})");
|
2023-11-08 19:57:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
} else {
|
|
|
|
throw ArgumentError("Invalid fee rate argument provided!");
|
|
|
|
}
|
|
|
|
} catch (e, s) {
|
2024-05-15 21:20:45 +00:00
|
|
|
Logging.instance.log(
|
|
|
|
"Exception rethrown from prepareSend(): $e\n$s",
|
|
|
|
level: LogLevel.Error,
|
|
|
|
);
|
2023-11-08 19:57:38 +00:00
|
|
|
rethrow;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-14 19:21:21 +00:00
|
|
|
@override
|
|
|
|
Future<void> init() async {
|
|
|
|
try {
|
2023-11-14 20:31:53 +00:00
|
|
|
final features = await electrumXClient
|
2023-11-14 19:21:21 +00:00
|
|
|
.getServerFeatures()
|
2024-01-29 04:29:07 +00:00
|
|
|
.timeout(const Duration(seconds: 5));
|
2023-11-14 19:21:21 +00:00
|
|
|
|
|
|
|
Logging.instance.log("features: $features", level: LogLevel.Info);
|
|
|
|
|
|
|
|
_serverVersion =
|
|
|
|
_parseServerVersion(features["server_version"] as String);
|
|
|
|
|
|
|
|
if (cryptoCurrency.genesisHash != features['genesis_hash']) {
|
|
|
|
throw Exception("genesis hash does not match!");
|
|
|
|
}
|
|
|
|
} catch (e, s) {
|
2024-01-12 19:56:09 +00:00
|
|
|
// do nothing, still allow user into wallet
|
|
|
|
Logging.instance.log(
|
2024-01-29 04:29:07 +00:00
|
|
|
"$runtimeType init() did not complete: $e\n$s",
|
|
|
|
level: LogLevel.Warning,
|
2024-01-12 19:56:09 +00:00
|
|
|
);
|
2023-11-14 19:21:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
await super.init();
|
|
|
|
}
|
|
|
|
|
2023-11-03 19:46:55 +00:00
|
|
|
// ===========================================================================
|
|
|
|
// ========== Interface functions ============================================
|
|
|
|
|
2023-11-08 19:57:38 +00:00
|
|
|
int estimateTxFee({required int vSize, required int feeRatePerKB});
|
2023-11-03 19:46:55 +00:00
|
|
|
Amount roughFeeEstimate(int inputCount, int outputCount, int feeRatePerKB);
|
|
|
|
|
2023-11-29 15:53:30 +00:00
|
|
|
Future<List<Address>> fetchAddressesForElectrumXScan();
|
2023-11-06 23:10:07 +00:00
|
|
|
|
2023-11-07 16:25:04 +00:00
|
|
|
/// Certain coins need to check if the utxo should be marked
|
2023-11-06 23:10:07 +00:00
|
|
|
/// as blocked as well as give a reason.
|
2024-01-05 00:37:46 +00:00
|
|
|
Future<({String? blockedReason, bool blocked, String? utxoLabel})>
|
|
|
|
checkBlockUTXO(
|
2023-11-06 23:10:07 +00:00
|
|
|
Map<String, dynamic> jsonUTXO,
|
|
|
|
String? scriptPubKeyHex,
|
|
|
|
Map<String, dynamic> jsonTX,
|
2024-01-05 00:37:46 +00:00
|
|
|
String? utxoOwnerAddress,
|
2023-11-06 23:10:07 +00:00
|
|
|
);
|
|
|
|
|
2023-11-03 19:46:55 +00:00
|
|
|
// ===========================================================================
|
|
|
|
// ========== private helpers ================================================
|
|
|
|
|
|
|
|
List<UTXO> _spendableUTXOs(List<UTXO> utxos) {
|
|
|
|
return utxos
|
|
|
|
.where(
|
|
|
|
(e) =>
|
|
|
|
!e.isBlocked &&
|
|
|
|
e.isConfirmed(
|
|
|
|
info.cachedChainHeight,
|
|
|
|
cryptoCurrency.minConfirms,
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.toList();
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<Amount> _sweepAllEstimate(int feeRate, List<UTXO> usableUTXOs) async {
|
|
|
|
final available = usableUTXOs
|
|
|
|
.map((e) => BigInt.from(e.value))
|
|
|
|
.fold(BigInt.zero, (p, e) => p + e);
|
|
|
|
final inputCount = usableUTXOs.length;
|
|
|
|
|
|
|
|
// transaction will only have 1 output minus the fee
|
|
|
|
final estimatedFee = roughFeeEstimate(inputCount, 1, feeRate);
|
|
|
|
|
|
|
|
return Amount(
|
|
|
|
rawValue: available,
|
2024-05-15 21:20:45 +00:00
|
|
|
fractionDigits: info.coin.fractionDigits,
|
2023-11-03 19:46:55 +00:00
|
|
|
) -
|
|
|
|
estimatedFee;
|
|
|
|
}
|
|
|
|
|
2023-11-14 19:21:21 +00:00
|
|
|
// stupid + fragile
|
2024-01-14 17:26:52 +00:00
|
|
|
List<int>? _parseServerVersion(String version) {
|
|
|
|
List<int>? result;
|
2023-11-14 19:21:21 +00:00
|
|
|
try {
|
|
|
|
final list = version.split(" ");
|
|
|
|
if (list.isNotEmpty) {
|
|
|
|
final numberStrings = list.last.split(".");
|
|
|
|
|
2024-01-14 17:26:52 +00:00
|
|
|
result = numberStrings.map((e) => int.parse(e)).toList();
|
2023-11-14 19:21:21 +00:00
|
|
|
}
|
|
|
|
} catch (_) {}
|
|
|
|
|
|
|
|
Logging.instance.log(
|
|
|
|
"${info.name} _parseServerVersion($version) => $result",
|
|
|
|
level: LogLevel.Info,
|
|
|
|
);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2024-01-12 20:49:05 +00:00
|
|
|
// lolcashaddrs
|
|
|
|
String normalizeAddress(String address) {
|
|
|
|
return address;
|
|
|
|
}
|
|
|
|
|
2023-11-03 19:46:55 +00:00
|
|
|
// ===========================================================================
|
2023-09-18 21:28:31 +00:00
|
|
|
}
|