feat: p2tr spend

This commit is contained in:
Rafael Saes 2023-11-18 16:38:00 -03:00
parent 2f6ad5248d
commit ae6c72909a
2 changed files with 175 additions and 178 deletions

View file

@ -189,6 +189,7 @@ abstract class ElectrumWalletBase
@override
Future<PendingTransaction> createTransaction(Object credentials) async {
try {
const minAmount = 546;
final transactionCredentials = credentials as BitcoinTransactionCredentials;
final inputs = <BitcoinUnspent>[];
@ -200,7 +201,8 @@ abstract class ElectrumWalletBase
await updateUnspent();
}
for (final utx in unspentCoins) {
for (int i = 0; i < unspentCoins.length; i++) {
final utx = unspentCoins[i];
if (utx.isSending) {
allInputsAmount += utx.value;
inputs.add(utx);
@ -270,26 +272,84 @@ abstract class ElectrumWalletBase
// throw BitcoinTransactionWrongBalanceException(currency);
}
final txb = bitcoin.TransactionBuilder(network: networkType);
final changeAddress = await walletAddresses.getChangeAddress();
var leftAmount = totalAmount;
var totalInputAmount = 0;
inputs.clear();
final txb = bitcoin.TransactionBuilder(network: networkType, version: 1);
for (final utx in unspentCoins) {
if (utx.isSending) {
leftAmount = leftAmount - utx.value;
List<bitcoin.PrivateKeyInfo> inputPrivKeys = [];
List<bitcoin.Outpoint> outpoints = [];
for (int i = 0; i < inputs.length; i++) {
final utx = inputs[i];
leftAmount = utx.value - leftAmount;
totalInputAmount += utx.value;
inputs.add(utx);
if (leftAmount <= 0) {
break;
}
}
final isSilentPayment = utx.bitcoinAddressRecord.silentPaymentTweak != null;
outpoints.add(bitcoin.Outpoint(txid: utx.hash, index: utx.vout));
if (isSilentPayment) {
// https://github.com/bitcoin/bips/blob/c55f80c53c98642357712c1839cfdc0551d531c4/bip-0352.mediawiki#user-content-Spending
final d = bitcoin.PrivateKey.fromHex(bitcoin.getSecp256k1(),
walletAddresses.silentAddress!.spendPrivkey.toCompressedHex())
.tweakAdd(utx.bitcoinAddressRecord.silentPaymentTweak!.bigint)!;
inputPrivKeys.add(bitcoin.PrivateKeyInfo(d, true));
final point = bitcoin.ECPublic.fromHex(d.publicKey.toHex()).toTapPoint();
final p2tr = bitcoin.P2trAddress(program: point);
bitcoin.ECPair keyPair = bitcoin.ECPair.fromPrivateKey(d.toCompressedHex().fromHex,
compressed: true, network: networkType);
txb.addInput(
utx.hash, utx.vout, null, p2tr.toScriptPubKey().toBytes(), keyPair, utx.value);
continue;
}
if (inputs.isEmpty) {
inputPrivKeys.add(bitcoin.PrivateKeyInfo(
bitcoin.PrivateKey.fromHex(
bitcoin.getSecp256k1(),
generateKeyPair(
hd: utx.bitcoinAddressRecord.isHidden
? walletAddresses.sideHd
: walletAddresses.mainHd,
index: utx.bitcoinAddressRecord.index,
network: networkType)
.privateKey!
.hex),
false));
bitcoin.ECPair keyPair = generateKeyPair(
hd: utx.bitcoinAddressRecord.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd,
index: utx.bitcoinAddressRecord.index,
network: networkType);
if (utx.isP2wpkh) {
final p2wpkh = bitcoin
.P2WPKH(
data: generatePaymentData(
hd: utx.bitcoinAddressRecord.isHidden
? walletAddresses.sideHd
: walletAddresses.mainHd,
index: utx.bitcoinAddressRecord.index),
network: networkType)
.data;
txb.addInput(utx.hash, utx.vout, null, p2wpkh.output, keyPair, utx.value);
continue;
}
txb.addInput(utx.hash, utx.vout, null, null, keyPair, utx.value);
}
if (txb.inputs.isEmpty) {
throw BitcoinTransactionNoInputsException();
}
@ -297,87 +357,28 @@ abstract class ElectrumWalletBase
// throw BitcoinTransactionWrongBalanceException(currency);
}
txb.setVersion(1);
List<bitcoin.PrivateKeyInfo> inputPrivKeys = [];
List<bitcoin.Outpoint> outpoints = [];
inputs.forEach((input) {
final isSilentPayment = input.bitcoinAddressRecord.silentPaymentTweak != null;
outpoints.add(bitcoin.Outpoint(txid: input.hash, index: input.vout));
if (isSilentPayment) {
// https://github.com/bitcoin/bips/blob/c55f80c53c98642357712c1839cfdc0551d531c4/bip-0352.mediawiki#user-content-Spending
final d = walletAddresses.silentAddress!.spendPrivkey
.tweakAdd(input.bitcoinAddressRecord.silentPaymentTweak!.bigint)!;
inputPrivKeys.add(bitcoin.PrivateKeyInfo(d, true));
print(["output", d]);
final p2tr = bitcoin
.P2TR(
data: bitcoin.PaymentData(pubkey: d.publicKey.toCompressedHex().fromHex),
network: networkType)
.data;
print(["output", p2tr.output]);
txb.addInput(input.hash, input.vout, null, p2tr.output);
} else {
inputPrivKeys.add(bitcoin.PrivateKeyInfo(
bitcoin.PrivateKey.fromHex(
bitcoin.getSecp256k1(),
generateKeyPair(
hd: input.bitcoinAddressRecord.isHidden
? walletAddresses.sideHd
: walletAddresses.mainHd,
index: input.bitcoinAddressRecord.index,
network: networkType)
.privateKey!
.hex),
false));
if (input.isP2wpkh) {
final p2wpkh = bitcoin
.P2WPKH(
data: generatePaymentData(
hd: input.bitcoinAddressRecord.isHidden
? walletAddresses.sideHd
: walletAddresses.mainHd,
index: input.bitcoinAddressRecord.index),
network: networkType)
.data;
txb.addInput(input.hash, input.vout, null, p2wpkh.output);
} else {
txb.addInput(input.hash, input.vout);
}
}
});
List<bitcoin.SilentPaymentDestination> silentAddresses = [];
List<bitcoin.SilentPaymentDestination> silentPaymentDestinations = [];
outputs.forEach((item) {
final outputAmount = hasMultiDestination ? item.formattedCryptoAmount : amount;
final outputAddress = item.isParsedAddress ? item.extractedAddress! : item.address;
if (outputAddress.startsWith('tsp1')) {
silentAddresses
silentPaymentDestinations
.add(bitcoin.SilentPaymentDestination.fromAddress(outputAddress, outputAmount!));
} else {
txb.addOutput(addressToOutputScript(outputAddress, networkType), outputAmount!);
}
});
if (silentAddresses.isNotEmpty) {
if (silentPaymentDestinations.isNotEmpty) {
final outpointsHash = bitcoin.SilentPayment.hashOutpoints(outpoints);
final aSum = bitcoin.SilentPayment.getSumInputPrivKeys(inputPrivKeys);
final generatedOutputs = bitcoin.SilentPayment.generateMultipleRecipientPubkeys(
aSum, outpointsHash, silentAddresses);
aSum, outpointsHash, silentPaymentDestinations);
generatedOutputs.forEach((recipientSilentAddress, generatedOutput) {
generatedOutput.forEach((output) {
final generatedPubkey = output.$1.toHex();
// TODO: pubkeyToOutputScript (?)
// TODO: DRY code: pubkeyToOutputScript (?)
final point = bitcoin.ECPublic.fromHex(generatedPubkey).toTapPoint();
final p2tr = bitcoin.P2trAddress(program: point);
txb.addOutput(p2tr.toScriptPubKey().toBytes(), amount);
@ -400,15 +401,10 @@ abstract class ElectrumWalletBase
txb.addOutput(changeAddress, changeValue);
}
final amounts = txb.inputs.map((utx) => utx.value!).toList();
final scriptPubKeys = txb.inputs.map((utx) => utx.prevOutScript!).toList();
for (var i = 0; i < inputs.length; i++) {
final input = inputs[i];
final keyPair = generateKeyPair(
hd: input.bitcoinAddressRecord.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd,
index: input.bitcoinAddressRecord.index,
network: networkType);
final witnessValue = input.isP2wpkh ? input.value : null;
txb.sign(vin: i, keyPair: keyPair, witnessValue: witnessValue);
txb.sign(vin: i, amounts: amounts, scriptPubKeys: scriptPubKeys, inputs: inputs);
}
return PendingBitcoinTransaction(txb.build(), type,
@ -417,6 +413,11 @@ abstract class ElectrumWalletBase
transactionHistory.addOne(transaction);
await updateBalance();
});
} catch (e, stacktrace) {
print(stacktrace);
print(e.toString());
rethrow;
}
}
String toJSON() => json.encode({
@ -712,9 +713,7 @@ abstract class ElectrumWalletBase
final normalizedHistories = <Map<String, dynamic>>[];
walletAddresses.addresses.forEach((addressRecord) {
if (addressRecord.address ==
"tb1pch9qmsq87wy4my4akd60x2r2yt784zfmfwqeuk7w7g7u45za4ktq9pdnmf") {
print(["during fetch txs", addressRecord.address, addressRecord.silentPaymentTweak]);
}
"tb1pch9qmsq87wy4my4akd60x2r2yt784zfmfwqeuk7w7g7u45za4ktq9pdnmf") {}
final sh = scriptHash(addressRecord.address, networkType: networkType);
addressHashes[sh] = addressRecord;
});

View file

@ -9,9 +9,7 @@ import 'package:cw_core/wallet_type.dart';
class PendingBitcoinTransaction with PendingTransaction {
PendingBitcoinTransaction(this._tx, this.type,
{required this.electrumClient,
required this.amount,
required this.fee})
{required this.electrumClient, required this.amount, required this.fee})
: _listeners = <void Function(ElectrumTransactionInfo transaction)>[];
final WalletType type;
@ -36,8 +34,9 @@ class PendingBitcoinTransaction with PendingTransaction {
@override
Future<void> commit() async {
print(["hex", _tx.txHex ?? _tx.toHex()]);
final result =
await electrumClient.broadcastTransaction(transactionRaw: _tx.toHex());
await electrumClient.broadcastTransaction(transactionRaw: _tx.txHex ?? _tx.toHex());
if (result.isEmpty) {
throw BitcoinCommitTransactionException();
@ -46,8 +45,7 @@ class PendingBitcoinTransaction with PendingTransaction {
_listeners?.forEach((listener) => listener(transactionInfo()));
}
void addListener(
void Function(ElectrumTransactionInfo transaction) listener) =>
void addListener(void Function(ElectrumTransactionInfo transaction) listener) =>
_listeners.add(listener);
ElectrumTransactionInfo transactionInfo() => ElectrumTransactionInfo(type,