Merge branch 'tests/bitcoindart-particl' into tests/particl

This commit is contained in:
sneurlax 2022-11-29 13:42:43 -06:00
commit 046a5c9506
6 changed files with 135 additions and 70 deletions

View file

@ -9,6 +9,7 @@ import 'package:stackwallet/services/coins/dogecoin/dogecoin_wallet.dart';
import 'package:stackwallet/services/coins/epiccash/epiccash_wallet.dart';
import 'package:stackwallet/services/coins/firo/firo_wallet.dart';
import 'package:stackwallet/services/coins/monero/monero_wallet.dart';
import 'package:stackwallet/services/coins/namecoin/namecoin_wallet.dart';
import 'package:stackwallet/services/coins/particl/particl_wallet.dart';
import 'package:stackwallet/services/coins/wownero/wownero_wallet.dart';
import 'package:stackwallet/services/transaction_notification_tracker.dart';
@ -186,6 +187,7 @@ abstract class CoinServiceAPI {
walletId: walletId,
walletName: walletName,
coin: coin,
secureStore: secureStorageInterface,
client: client,
cachedClient: cachedClient,
tracker: tracker);

View file

@ -10,8 +10,8 @@ import 'package:bitcoindart/bitcoindart.dart';
import 'package:bs58check/bs58check.dart' as bs58check;
import 'package:crypto/crypto.dart';
import 'package:decimal/decimal.dart';
import 'package:devicelocale/devicelocale.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart';
import 'package:stackwallet/electrumx_rpc/cached_electrumx.dart';
import 'package:stackwallet/electrumx_rpc/electrumx.dart';
@ -46,7 +46,7 @@ const int MINIMUM_CONFIRMATIONS = 1;
const int DUST_LIMIT = 294;
const String GENESIS_HASH_MAINNET =
"0000ee0784c195317ac95623e22fddb8c7b8825dc3998e0bb924d66866eccf4c";
"000000000062b72c5e2ceb45fbc8587e807c155b0da735e6483dfba2f0a9c770";
const String GENESIS_HASH_TESTNET =
"0000594ada5310b367443ee0afd4fa3d0bbd5850ea4e33cdc7d6a904a7ec7c90";
@ -194,20 +194,24 @@ class ParticlWallet extends CoinServiceAPI {
Future<Decimal> get availableBalance async {
final data = await utxoData;
return Format.satoshisToAmount(
data.satoshiBalance - data.satoshiBalanceUnconfirmed);
data.satoshiBalance - data.satoshiBalanceUnconfirmed,
coin: coin);
}
@override
Future<Decimal> get pendingBalance async {
final data = await utxoData;
return Format.satoshisToAmount(data.satoshiBalanceUnconfirmed);
return Format.satoshisToAmount(
data.satoshiBalanceUnconfirmed,
coin: coin);
}
@override
Future<Decimal> get balanceMinusMaxFee async =>
(await availableBalance) -
(Decimal.fromInt((await maxFee)) / Decimal.fromInt(Constants.satsPerCoin))
.toDecimal();
(Decimal.fromInt((await maxFee)) /
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toDecimal();
@override
Future<Decimal> get totalBalance async {
@ -216,13 +220,19 @@ class ParticlWallet extends CoinServiceAPI {
.get<dynamic>(boxName: walletId, key: 'totalBalance') as int?;
if (totalBalance == null) {
final data = await utxoData;
return Format.satoshisToAmount(data.satoshiBalance);
return Format.satoshisToAmount(
data.satoshiBalance,
coin: coin);
} else {
return Format.satoshisToAmount(totalBalance);
return Format.satoshisToAmount(
totalBalance,
coin: coin);
}
}
final data = await utxoData;
return Format.satoshisToAmount(data.satoshiBalance);
return Format.satoshisToAmount(
data.satoshiBalance,
coin: coin);
}
@override
@ -260,7 +270,8 @@ class ParticlWallet extends CoinServiceAPI {
@override
Future<int> get maxFee async {
final fee = (await fees).fast as String;
final satsFee = Decimal.parse(fee) * Decimal.fromInt(Constants.satsPerCoin);
final satsFee =
Decimal.parse(fee) * Decimal.fromInt(Constants.satsPerCoin(coin));
return satsFee.floor().toBigInt().toInt();
}
@ -437,8 +448,7 @@ class ParticlWallet extends CoinServiceAPI {
data: PaymentData(
redeem: P2WPKH(
data: PaymentData(pubkey: node.publicKey),
network: _network,
overridePrefix: particl.bech32!)
network: _network)
.data),
network: _network)
.data
@ -961,8 +971,6 @@ class ParticlWallet extends CoinServiceAPI {
if (currentHeight != storedHeight) {
if (currentHeight != -1) {
Logging.instance
.log("Can update chain: $currentHeight", level: LogLevel.Info);
// -1 failed to fetch current height
unawaited(updateStoredChainHeight(newHeight: currentHeight));
}
@ -1086,7 +1094,8 @@ class ParticlWallet extends CoinServiceAPI {
// check for send all
bool isSendAll = false;
final balance = Format.decimalAmountToSatoshis(await availableBalance);
final balance =
Format.decimalAmountToSatoshis(await availableBalance, coin);
if (satoshiAmount == balance) {
isSendAll = true;
}
@ -1276,9 +1285,58 @@ class ParticlWallet extends CoinServiceAPI {
_transactionData ??= _fetchTransactionData();
Future<TransactionData>? _transactionData;
TransactionData? cachedTxData;
// TODO make sure this copied implementation from bitcoin_wallet.dart applies for particl just as well--or import it
// hack to add tx to txData before refresh completes
// required based on current app architecture where we don't properly store
// transactions locally in a good way
@override
Future<void> updateSentCachedTxData(Map<String, dynamic> txData) async {
final priceData =
await _priceAPI.getPricesAnd24hChange(baseCurrency: _prefs.currency);
Decimal currentPrice = priceData[coin]?.item1 ?? Decimal.zero;
final locale = await Devicelocale.currentLocale;
final String worthNow = Format.localizedStringAsFixed(
value:
((currentPrice * Decimal.fromInt(txData["recipientAmt"] as int)) /
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toDecimal(scaleOnInfinitePrecision: 2),
decimalPlaces: 2,
locale: locale!);
final tx = models.Transaction(
txid: txData["txid"] as String,
confirmedStatus: false,
timestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000,
txType: "Sent",
amount: txData["recipientAmt"] as int,
worthNow: worthNow,
worthAtBlockTimestamp: worthNow,
fees: txData["fee"] as int,
inputSize: 0,
outputSize: 0,
inputs: [],
outputs: [],
address: txData["address"] as String,
height: -1,
confirmations: 0,
);
if (cachedTxData == null) {
final data = await _fetchTransactionData();
_transactionData = Future(() => data);
}
final transactions = cachedTxData!.getAllTransactions();
transactions[tx.txid] = tx;
cachedTxData = models.TransactionData.fromMap(transactions);
_transactionData = Future(() => cachedTxData!);
}
@override
bool validateAddress(String address) {
return Address.validateAddress(address, _network, particl.bech32!);
return Address.validateAddress(address, _network);
}
@override
@ -1313,7 +1371,7 @@ class ParticlWallet extends CoinServiceAPI {
required CachedElectrumX cachedClient,
required TransactionNotificationTracker tracker,
PriceAPI? priceAPI,
SecureStorageInterface? secureStore,
required SecureStorageInterface secureStore,
}) {
txTracker = tracker;
_walletId = walletId;
@ -1323,13 +1381,12 @@ class ParticlWallet extends CoinServiceAPI {
_cachedElectrumXClient = cachedClient;
_priceAPI = priceAPI ?? PriceAPI(Client());
_secureStore =
secureStore ?? const SecureStorageWrapper(FlutterSecureStorage());
_secureStore = secureStore;
}
@override
Future<void> updateNode(bool shouldRefresh) async {
final failovers = NodeService()
final failovers = NodeService(secureStorageInterface: _secureStore)
.failoverNodesFor(coin: coin)
.map((e) => ElectrumXNode(
address: e.host,
@ -1367,7 +1424,7 @@ class ParticlWallet extends CoinServiceAPI {
}
Future<ElectrumXNode> getCurrentNode() async {
final node = NodeService().getPrimaryNodeFor(coin: coin) ??
final node = NodeService(secureStorageInterface: _secureStore).getPrimaryNodeFor(coin: coin) ??
DefaultNodes.getNodeFor(coin);
return ElectrumXNode(
@ -1442,9 +1499,9 @@ class ParticlWallet extends CoinServiceAPI {
numberOfBlocksFast: f,
numberOfBlocksAverage: m,
numberOfBlocksSlow: s,
fast: Format.decimalAmountToSatoshis(fast),
medium: Format.decimalAmountToSatoshis(medium),
slow: Format.decimalAmountToSatoshis(slow),
fast: Format.decimalAmountToSatoshis(fast, coin),
medium: Format.decimalAmountToSatoshis(medium, coin),
slow: Format.decimalAmountToSatoshis(slow, coin),
);
Logging.instance.log("fetched fees: $feeObject", level: LogLevel.Info);
@ -1625,11 +1682,7 @@ class ParticlWallet extends CoinServiceAPI {
case DerivePathType.bip49:
address = P2SH(
data: PaymentData(
redeem: P2WPKH(
data: data,
network: _network,
overridePrefix: particl.bech32!)
.data),
redeem: P2WPKH(data: data, network: _network).data),
network: _network)
.data
.address!;
@ -1912,7 +1965,7 @@ class ParticlWallet extends CoinServiceAPI {
utxo["status"]["block_time"] = txn["blocktime"];
final fiatValue = ((Decimal.fromInt(value) * currentPrice) /
Decimal.fromInt(Constants.satsPerCoin))
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toDecimal(scaleOnInfinitePrecision: 2);
utxo["rawWorth"] = fiatValue;
utxo["fiatWorth"] = fiatValue.toString();
@ -1921,16 +1974,17 @@ class ParticlWallet extends CoinServiceAPI {
}
Decimal currencyBalanceRaw =
((Decimal.fromInt(satoshiBalance) * currentPrice) /
Decimal.fromInt(Constants.satsPerCoin))
.toDecimal(scaleOnInfinitePrecision: 2);
((Decimal.fromInt(satoshiBalance) * currentPrice) /
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toDecimal(scaleOnInfinitePrecision: 2);
final Map<String, dynamic> result = {
"total_user_currency": currencyBalanceRaw.toString(),
"total_sats": satoshiBalance,
"total_btc": (Decimal.fromInt(satoshiBalance) /
Decimal.fromInt(Constants.satsPerCoin))
.toDecimal(scaleOnInfinitePrecision: Constants.decimalPlaces)
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toDecimal(
scaleOnInfinitePrecision: Constants.decimalPlacesForCoin(coin))
.toString(),
"outputArray": outputArray,
"unconfirmed": satoshiBalancePending,
@ -2433,9 +2487,6 @@ class ParticlWallet extends CoinServiceAPI {
coin: coin,
);
Logging.instance
.log("RECEIVED TX IS : ${tx["vout"]}", level: LogLevel.Info);
for (final out in tx["vout"] as List) {
if (prevOut == out["n"]) {
final address = out["scriptPubKey"]["address"] as String?;
@ -2479,7 +2530,7 @@ class ParticlWallet extends CoinServiceAPI {
if (prevOut == out["n"]) {
inputAmtSentFromWallet +=
(Decimal.parse(out["value"]!.toString()) *
Decimal.fromInt(Constants.satsPerCoin))
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toBigInt()
.toInt();
}
@ -2492,7 +2543,7 @@ class ParticlWallet extends CoinServiceAPI {
final String address = output["scriptPubKey"]!["address"] as String;
final value = output["value"]!;
final _value = (Decimal.parse(value.toString()) *
Decimal.fromInt(Constants.satsPerCoin))
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toBigInt()
.toInt();
totalOutput += _value;
@ -2517,7 +2568,7 @@ class ParticlWallet extends CoinServiceAPI {
final address = output["scriptPubKey"]["address"];
if (address != null) {
final value = (Decimal.parse(output["value"].toString()) *
Decimal.fromInt(Constants.satsPerCoin))
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toBigInt()
.toInt();
totalOut += value;
@ -2540,7 +2591,7 @@ class ParticlWallet extends CoinServiceAPI {
for (final out in tx["vout"] as List) {
if (prevOut == out["n"]) {
totalIn += (Decimal.parse(out["value"].toString()) *
Decimal.fromInt(Constants.satsPerCoin))
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toBigInt()
.toInt();
}
@ -2562,7 +2613,7 @@ class ParticlWallet extends CoinServiceAPI {
midSortedTx["amount"] = inputAmtSentFromWallet;
final String worthNow =
((currentPrice * Decimal.fromInt(inputAmtSentFromWallet)) /
Decimal.fromInt(Constants.satsPerCoin))
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toDecimal(scaleOnInfinitePrecision: 2)
.toStringAsFixed(2);
midSortedTx["worthNow"] = worthNow;
@ -2572,7 +2623,7 @@ class ParticlWallet extends CoinServiceAPI {
midSortedTx["amount"] = outputAmtAddressedToWallet;
final worthNow =
((currentPrice * Decimal.fromInt(outputAmtAddressedToWallet)) /
Decimal.fromInt(Constants.satsPerCoin))
Decimal.fromInt(Constants.satsPerCoin(coin)))
.toDecimal(scaleOnInfinitePrecision: 2)
.toStringAsFixed(2);
midSortedTx["worthNow"] = worthNow;
@ -2694,6 +2745,14 @@ class ParticlWallet extends CoinServiceAPI {
spendableOutputs.sort(
(a, b) => b.status.confirmations.compareTo(a.status.confirmations));
Logging.instance.log("spendableOutputs.length: ${spendableOutputs.length}",
level: LogLevel.Info);
Logging.instance
.log("spendableOutputs: $spendableOutputs", level: LogLevel.Info);
Logging.instance.log("spendableSatoshiValue: $spendableSatoshiValue",
level: LogLevel.Info);
Logging.instance
.log("satoshiAmountToSend: $satoshiAmountToSend", level: LogLevel.Info);
// If the amount the user is trying to send is smaller than the amount that they have spendable,
// then return 1, which indicates that they have an insufficient balance.
if (spendableSatoshiValue < satoshiAmountToSend) {
@ -2728,6 +2787,13 @@ class ParticlWallet extends CoinServiceAPI {
inputsBeingConsumed += 1;
}
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
List<String> recipientsArray = [_recipientAddress];
List<int> recipientsAmtArray = [satoshiAmountToSend];
@ -3015,9 +3081,7 @@ class ParticlWallet extends CoinServiceAPI {
for (final output in tx["vout"] as List) {
final n = output["n"];
if (n != null && n == utxosToUse[i].vout) {
Logging.instance.log("THIS OUTPUT IS ${output["scriptPubKey"]}",
level: LogLevel.Info, printFullLength: true);
final address = output["scriptPubKey"]["addresses"][0] as String;
final address = output["scriptPubKey"]["address"] as String;
if (!addressTxid.containsKey(address)) {
addressTxid[address] = <String>[];
}
@ -3039,9 +3103,6 @@ class ParticlWallet extends CoinServiceAPI {
// p2pkh / bip44
final p2pkhLength = addressesP2PKH.length;
Logging.instance
.log("THE BIP44 LENGTH IS $p2pkhLength", level: LogLevel.Info);
if (p2pkhLength > 0) {
final receiveDerivations = await _fetchDerivations(
chain: 0,
@ -3100,8 +3161,6 @@ class ParticlWallet extends CoinServiceAPI {
// p2sh / bip49
final p2shLength = addressesP2SH.length;
Logging.instance
.log("THE BIP49 LENGTH IS $p2pkhLength", level: LogLevel.Info);
if (p2shLength > 0) {
final receiveDerivations = await _fetchDerivations(
chain: 0,
@ -3120,8 +3179,7 @@ class ParticlWallet extends CoinServiceAPI {
data: PaymentData(
pubkey: Format.stringToUint8List(
receiveDerivation["pubKey"] as String)),
network: _network,
overridePrefix: particl.bech32!)
network: _network)
.data;
final redeemScript = p2wpkh.output;
@ -3250,7 +3308,7 @@ class ParticlWallet extends CoinServiceAPI {
.log("Starting buildTransaction ----------", level: LogLevel.Info);
final txb = TransactionBuilder(network: _network);
txb.setVersion(160);
txb.setVersion(1);
// Add transaction inputs
for (var i = 0; i < utxosToUse.length; i++) {
@ -3261,20 +3319,19 @@ class ParticlWallet extends CoinServiceAPI {
// Add transaction output
for (var i = 0; i < recipients.length; i++) {
txb.addOutput(recipients[i], satoshiAmounts[i], particl.bech32!);
txb.addOutput(recipients[i], satoshiAmounts[i]);
}
try {
// Sign the transaction accordingly
for (var i = 0; i < utxosToUse.length; i++) {
final txid = utxosToUse[i].txid;
txb.sign(
vin: i,
keyPair: utxoSigningData[txid]["keyPair"] as ECPair,
witnessValue: utxosToUse[i].value,
redeemScript: utxoSigningData[txid]["redeemScript"] as Uint8List?,
overridePrefix: particl.bech32!);
vin: i,
keyPair: utxoSigningData[txid]["keyPair"] as ECPair,
witnessValue: utxosToUse[i].value,
redeemScript: utxoSigningData[txid]["redeemScript"] as Uint8List?,
);
}
} catch (e, s) {
Logging.instance.log("Caught exception while signing transaction: $e\n$s",
@ -3282,8 +3339,7 @@ class ParticlWallet extends CoinServiceAPI {
rethrow;
}
final builtTx = txb.build(particl.bech32!);
print("BUILT TX IS $builtTx");
final builtTx = txb.build();
final vSize = builtTx.virtualSize();
return {"hex": builtTx.toHex(), "vSize": vSize};
@ -3694,7 +3750,7 @@ class ParticlWallet extends CoinServiceAPI {
@override
Future<int> estimateFeeFor(int satoshiAmount, int feeRate) async {
final available = Format.decimalAmountToSatoshis(await availableBalance);
final available = Format.decimalAmountToSatoshis(await availableBalance, coin);
if (available == satoshiAmount) {
return satoshiAmount - sweepAllEstimate(feeRate);

View file

@ -54,6 +54,7 @@ abstract class Constants {
case Coin.firoTestNet:
case Coin.epicCash:
case Coin.namecoin:
case Coin.particl:
return _satsPerCoin;
case Coin.wownero:
@ -78,6 +79,7 @@ abstract class Constants {
case Coin.firoTestNet:
case Coin.epicCash:
case Coin.namecoin:
case Coin.particl:
return _decimalPlaces;
case Coin.wownero:

View file

@ -146,15 +146,15 @@ abstract class DefaultNodes {
);
static NodeModel get particl => NodeModel(
host: "particl.stackwallet.com",
port: 58002,
host: "164.92.93.20",
port: 50002,
name: defaultName,
id: _nodeId(Coin.particl),
useSSL: true,
enabled: true,
coinName: Coin.particl.name,
isFailover: true,
isDown: false);
isDown: false); //TODO - UPDATE WITH CORRECT DETAILS
static NodeModel get bitcoinTestnet => NodeModel(
host: "electrumx-testnet.cypherstack.com",

View file

@ -15,6 +15,8 @@ import 'package:stackwallet/services/coins/wownero/wownero_wallet.dart' as wow;
import 'package:stackwallet/services/coins/particl/particl_wallet.dart'
as particl;
import 'package:stackwallet/utilities/util.dart';
import 'package:stackwallet/services/coins/particl/particl_wallet.dart'
as particl;
enum Coin {
bitcoin,
@ -24,6 +26,7 @@ enum Coin {
firo,
litecoin,
monero,
namecoin,
particl,
wownero,
@ -313,6 +316,8 @@ Coin coinFromTickerCaseInsensitive(String ticker) {
return Coin.particl;
case "tltc":
return Coin.litecoinTestNet;
case "part":
return Coin.particl;
case "tbtc":
return Coin.bitcoinTestNet;
case "tbch":

View file

@ -106,7 +106,7 @@ void main() {
late FakeSecureStorage secureStore;
MockTransactionNotificationTracker? tracker;
NamecoinWallet? mainnetWallet;
ParticlWallet? mainnetWallet;
setUp(() {
client = MockElectrumX();
@ -115,7 +115,7 @@ void main() {
secureStore = FakeSecureStorage();
tracker = MockTransactionNotificationTracker();
mainnetWallet = NamecoinWallet(
mainnetWallet = ParticlWallet(
walletId: "validateAddressMainNet",
walletName: "validateAddressMainNet",
coin: Coin.particl,