Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/cake-tech/cake_wallet into …
Browse files Browse the repository at this point in the history
…CW-732-CI-Automation-For-Testing
  • Loading branch information
Blazebrain committed Nov 28, 2024
2 parents 5697298 + 4ca50b5 commit 097340a
Show file tree
Hide file tree
Showing 51 changed files with 716 additions and 292 deletions.
145 changes: 113 additions & 32 deletions cw_bitcoin/lib/electrum_wallet.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1503,14 +1503,21 @@ abstract class ElectrumWalletBase
final bundle = await getTransactionExpanded(hash: txId);
final outputs = bundle.originalTransaction.outputs;

final changeAddresses = walletAddresses.allAddresses.where((element) => element.isHidden);
final ownAddresses = walletAddresses.allAddresses.map((addr) => addr.address).toSet();

// look for a change address in the outputs
final changeOutput = outputs.firstWhereOrNull((output) => changeAddresses.any(
(element) => element.address == addressFromOutputScript(output.scriptPubKey, network)));
final receiverAmount = outputs
.where((output) => !ownAddresses.contains(addressFromOutputScript(output.scriptPubKey, network)))
.fold<int>(0, (sum, output) => sum + output.amount.toInt());

var allInputsAmount = 0;
if (receiverAmount == 0) {
throw Exception("Receiver output not found.");
}

final availableInputs = unspentCoins.where((utxo) => utxo.isSending && !utxo.isFrozen).toList();
int totalBalance = availableInputs.fold<int>(
0, (previousValue, element) => previousValue + element.value.toInt());

int allInputsAmount = 0;
for (int i = 0; i < bundle.originalTransaction.inputs.length; i++) {
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
Expand All @@ -1521,25 +1528,24 @@ abstract class ElectrumWalletBase

int totalOutAmount = bundle.originalTransaction.outputs
.fold<int>(0, (previousValue, element) => previousValue + element.amount.toInt());

var currentFee = allInputsAmount - totalOutAmount;

int remainingFee = (newFee - currentFee > 0) ? newFee - currentFee : newFee;

return changeOutput != null && changeOutput.amount.toInt() - remainingFee >= 0;
return totalBalance - receiverAmount - remainingFee >= _dustAmount;
}

Future<PendingBitcoinTransaction> replaceByFee(String hash, int newFee) async {
try {
final bundle = await getTransactionExpanded(hash: hash);

final utxos = <UtxoWithAddress>[];
final outputs = <BitcoinOutput>[];
List<ECPrivate> privateKeys = [];

var allInputsAmount = 0;
String? memo;

// Add inputs
// Add original inputs
for (var i = 0; i < bundle.originalTransaction.inputs.length; i++) {
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
Expand All @@ -1549,8 +1555,7 @@ abstract class ElectrumWalletBase
allInputsAmount += outTransaction.amount.toInt();

final addressRecord =
walletAddresses.allAddresses.firstWhere((element) => element.address == address);

walletAddresses.allAddresses.firstWhere((element) => element.address == address);
final btcAddress = RegexUtils.addressTypeFromStr(addressRecord.address, network);
final privkey = generateECPrivate(
hd: addressRecord.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd,
Expand All @@ -1568,15 +1573,13 @@ abstract class ElectrumWalletBase
scriptType: _getScriptType(btcAddress),
),
ownerDetails:
UtxoAddressDetails(publicKey: privkey.getPublic().toHex(), address: btcAddress),
UtxoAddressDetails(publicKey: privkey.getPublic().toHex(), address: btcAddress),
),
);
}

// Create a list of available outputs
final outputs = <BitcoinOutput>[];
// Add original outputs
for (final out in bundle.originalTransaction.outputs) {
// Check if the script contains OP_RETURN
final script = out.scriptPubKey.script;
if (script.contains('OP_RETURN') && memo == null) {
final index = script.indexOf('OP_RETURN');
Expand All @@ -1598,25 +1601,103 @@ abstract class ElectrumWalletBase

// Calculate the total amount and fees
int totalOutAmount =
outputs.fold<int>(0, (previousValue, output) => previousValue + output.value.toInt());
outputs.fold<int>(0, (previousValue, output) => previousValue + output.value.toInt());
int currentFee = allInputsAmount - totalOutAmount;
int remainingFee = newFee - currentFee;

if (remainingFee <= 0) {
throw Exception("New fee must be higher than the current fee.");
}

// Deduct Remaining Fee from Main Outputs
// Deduct fee from change outputs first, if possible
if (remainingFee > 0) {
final changeAddresses = walletAddresses.allAddresses.where((element) => element.isHidden);
for (int i = outputs.length - 1; i >= 0; i--) {
int outputAmount = outputs[i].value.toInt();
final output = outputs[i];
final isChange = changeAddresses
.any((element) => element.address == output.address.toAddress(network));

if (isChange) {
int outputAmount = output.value.toInt();
if (outputAmount > _dustAmount) {
int deduction = (outputAmount - _dustAmount >= remainingFee)
? remainingFee
: outputAmount - _dustAmount;
outputs[i] = BitcoinOutput(
address: output.address, value: BigInt.from(outputAmount - deduction));
remainingFee -= deduction;

if (remainingFee <= 0) break;
}
}
}
}

// If still not enough, add UTXOs until the fee is covered
if (remainingFee > 0) {
final unusedUtxos = unspentCoins
.where((utxo) => utxo.isSending && !utxo.isFrozen && utxo.confirmations! > 0)
.toList();

for (final utxo in unusedUtxos) {
final address = RegexUtils.addressTypeFromStr(utxo.address, network);
final privkey = generateECPrivate(
hd: utxo.bitcoinAddressRecord.isHidden
? walletAddresses.sideHd
: walletAddresses.mainHd,
index: utxo.bitcoinAddressRecord.index,
network: network,
);
privateKeys.add(privkey);

utxos.add(UtxoWithAddress(
utxo: BitcoinUtxo(
txHash: utxo.hash,
value: BigInt.from(utxo.value),
vout: utxo.vout,
scriptType: _getScriptType(address)),
ownerDetails:
UtxoAddressDetails(publicKey: privkey.getPublic().toHex(), address: address),
));

allInputsAmount += utxo.value;
remainingFee -= utxo.value;

if (remainingFee < 0) {
final changeOutput = outputs.firstWhereOrNull((output) => walletAddresses.allAddresses
.any((addr) => addr.address == output.address.toAddress(network)));
if (changeOutput != null) {
final newValue = changeOutput.value.toInt() + (-remainingFee);
outputs[outputs.indexOf(changeOutput)] =
BitcoinOutput(address: changeOutput.address, value: BigInt.from(newValue));
} else {
final changeAddress = await walletAddresses.getChangeAddress();
outputs.add(BitcoinOutput(
address: RegexUtils.addressTypeFromStr(changeAddress.address, network),
value: BigInt.from(-remainingFee)));
}

remainingFee = 0;
break;
}

if (remainingFee <= 0) break;
}
}

// Deduct from the receiver's output if remaining fee is still greater than 0
if (remainingFee > 0) {
for (int i = 0; i < outputs.length; i++) {
final output = outputs[i];
int outputAmount = output.value.toInt();

if (outputAmount > _dustAmount) {
int deduction = (outputAmount - _dustAmount >= remainingFee)
? remainingFee
: outputAmount - _dustAmount;

outputs[i] = BitcoinOutput(
address: outputs[i].address, value: BigInt.from(outputAmount - deduction));
address: output.address, value: BigInt.from(outputAmount - deduction));
remainingFee -= deduction;

if (remainingFee <= 0) break;
Expand All @@ -1633,11 +1714,11 @@ abstract class ElectrumWalletBase
final changeAddresses = walletAddresses.allAddresses.where((element) => element.isHidden);
final List<BitcoinOutput> changeOutputs = outputs
.where((output) => changeAddresses
.any((element) => element.address == output.address.toAddress(network)))
.any((element) => element.address == output.address.toAddress(network)))
.toList();

int totalChangeAmount =
changeOutputs.fold<int>(0, (sum, output) => sum + output.value.toInt());
changeOutputs.fold<int>(0, (sum, output) => sum + output.value.toInt());

// The final amount that the receiver will receive
int sendingAmount = allInputsAmount - newFee - totalChangeAmount;
Expand All @@ -1654,8 +1735,7 @@ abstract class ElectrumWalletBase

final transaction = txb.buildTransaction((txDigest, utxo, publicKey, sighash) {
final key =
privateKeys.firstWhereOrNull((element) => element.getPublic().toHex() == publicKey);

privateKeys.firstWhereOrNull((element) => element.getPublic().toHex() == publicKey);
if (key == null) {
throw Exception("Cannot find private key");
}
Expand All @@ -1665,6 +1745,7 @@ abstract class ElectrumWalletBase
} else {
return key.signInput(txDigest, sigHash: sighash);
}

});

return PendingBitcoinTransaction(
Expand All @@ -1677,16 +1758,16 @@ abstract class ElectrumWalletBase
hasChange: changeOutputs.isNotEmpty,
feeRate: newFee.toString(),
)..addListener((transaction) async {
transactionHistory.transactions.values.forEach((tx) {
if (tx.id == hash) {
tx.isReplaced = true;
tx.isPending = false;
transactionHistory.addOne(tx);
}
});
transactionHistory.addOne(transaction);
await updateBalance();
transactionHistory.transactions.values.forEach((tx) {
if (tx.id == hash) {
tx.isReplaced = true;
tx.isPending = false;
transactionHistory.addOne(tx);
}
});
transactionHistory.addOne(transaction);
await updateBalance();
});
} catch (e) {
throw e;
}
Expand Down
12 changes: 12 additions & 0 deletions cw_monero/lib/api/coins_info.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@ int countOfCoins() => monero.Coins_count(coins!);

monero.CoinsInfo getCoin(int index) => monero.Coins_coin(coins!, index);

int? getCoinByKeyImage(String keyImage) {
final count = countOfCoins();
for (int i = 0; i < count; i++) {
final coin = getCoin(i);
final coinAddress = monero.CoinsInfo_keyImage(coin);
if (keyImage == coinAddress) {
return i;
}
}
return null;
}

void freezeCoin(int index) => monero.Coins_setFrozen(coins!, index: index);

void thawCoin(int index) => monero.Coins_thaw(coins!, index: index);
7 changes: 6 additions & 1 deletion cw_monero/lib/api/transaction_history.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:cw_monero/api/exceptions/creation_transaction_exception.dart';
import 'package:cw_monero/api/monero_output.dart';
import 'package:cw_monero/api/structs/pending_transaction.dart';
import 'package:cw_monero/api/wallet.dart';
import 'package:cw_monero/exceptions/monero_transaction_creation_exception.dart';
import 'package:ffi/ffi.dart';
import 'package:monero/monero.dart' as monero;
import 'package:monero/src/generated_bindings_monero.g.dart' as monero_gen;
Expand Down Expand Up @@ -101,7 +102,11 @@ Future<PendingTransactionDescription> createTransactionSync(
});

final address_ = address.toNativeUtf8();
final paymentId_ = paymentId.toNativeUtf8();
final paymentId_ = paymentId.toNativeUtf8();
if (preferredInputs.isEmpty) {
throw MoneroTransactionCreationException("No inputs provided, transaction cannot be constructed");
}

final preferredInputs_ = preferredInputs.join(monero.defaultSeparatorStr).toNativeUtf8();

final addraddr = address_.address;
Expand Down
10 changes: 10 additions & 0 deletions cw_monero/lib/api/wallet.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'dart:isolate';

import 'package:cw_monero/api/account_list.dart';
import 'package:cw_monero/api/exceptions/setup_wallet_exception.dart';
import 'package:flutter/foundation.dart';
import 'package:monero/monero.dart' as monero;
import 'package:mutex/mutex.dart';

Expand Down Expand Up @@ -129,6 +130,15 @@ Future<bool> setupNodeSync(
throw SetupWalletException(message: error);
}

if (kDebugMode) {
monero.Wallet_init3(
wptr!, argv0: '',
defaultLogBaseName: 'moneroc',
console: true,
logPath: '',
);
}

return status == 0;
}

Expand Down
24 changes: 23 additions & 1 deletion cw_monero/lib/monero_unspent.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,32 @@
import 'package:cw_core/unspent_transaction_output.dart';
import 'package:cw_monero/api/coins_info.dart';
import 'package:monero/monero.dart' as monero;

class MoneroUnspent extends Unspent {
MoneroUnspent(
String address, String hash, String keyImage, int value, bool isFrozen, this.isUnlocked)
: super(address, hash, value, 0, keyImage) {
this.isFrozen = isFrozen;
}

@override
set isFrozen(bool freeze) {
print("set isFrozen: $freeze ($keyImage): $freeze");
final coinId = getCoinByKeyImage(keyImage!);
if (coinId == null) throw Exception("Unable to find a coin for address $address");
if (freeze) {
freezeCoin(coinId);
} else {
thawCoin(coinId);
}
}

@override
bool get isFrozen {
print("get isFrozen");
final coinId = getCoinByKeyImage(keyImage!);
if (coinId == null) throw Exception("Unable to find a coin for address $address");
final coin = getCoin(coinId);
return monero.CoinsInfo_frozen(coin);
}

final bool isUnlocked;
Expand Down
Loading

0 comments on commit 097340a

Please sign in to comment.