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 @override
Future<PendingTransaction> createTransaction(Object credentials) async { Future<PendingTransaction> createTransaction(Object credentials) async {
try {
const minAmount = 546; const minAmount = 546;
final transactionCredentials = credentials as BitcoinTransactionCredentials; final transactionCredentials = credentials as BitcoinTransactionCredentials;
final inputs = <BitcoinUnspent>[]; final inputs = <BitcoinUnspent>[];
@ -200,7 +201,8 @@ abstract class ElectrumWalletBase
await updateUnspent(); await updateUnspent();
} }
for (final utx in unspentCoins) { for (int i = 0; i < unspentCoins.length; i++) {
final utx = unspentCoins[i];
if (utx.isSending) { if (utx.isSending) {
allInputsAmount += utx.value; allInputsAmount += utx.value;
inputs.add(utx); inputs.add(utx);
@ -270,26 +272,84 @@ abstract class ElectrumWalletBase
// throw BitcoinTransactionWrongBalanceException(currency); // throw BitcoinTransactionWrongBalanceException(currency);
} }
final txb = bitcoin.TransactionBuilder(network: networkType);
final changeAddress = await walletAddresses.getChangeAddress(); final changeAddress = await walletAddresses.getChangeAddress();
var leftAmount = totalAmount; var leftAmount = totalAmount;
var totalInputAmount = 0; var totalInputAmount = 0;
inputs.clear(); final txb = bitcoin.TransactionBuilder(network: networkType, version: 1);
for (final utx in unspentCoins) { List<bitcoin.PrivateKeyInfo> inputPrivKeys = [];
if (utx.isSending) { List<bitcoin.Outpoint> outpoints = [];
leftAmount = leftAmount - utx.value;
for (int i = 0; i < inputs.length; i++) {
final utx = inputs[i];
leftAmount = utx.value - leftAmount;
totalInputAmount += utx.value; totalInputAmount += utx.value;
inputs.add(utx);
if (leftAmount <= 0) { if (leftAmount <= 0) {
break; 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(); throw BitcoinTransactionNoInputsException();
} }
@ -297,87 +357,28 @@ abstract class ElectrumWalletBase
// throw BitcoinTransactionWrongBalanceException(currency); // throw BitcoinTransactionWrongBalanceException(currency);
} }
txb.setVersion(1); List<bitcoin.SilentPaymentDestination> silentPaymentDestinations = [];
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 = [];
outputs.forEach((item) { outputs.forEach((item) {
final outputAmount = hasMultiDestination ? item.formattedCryptoAmount : amount; final outputAmount = hasMultiDestination ? item.formattedCryptoAmount : amount;
final outputAddress = item.isParsedAddress ? item.extractedAddress! : item.address; final outputAddress = item.isParsedAddress ? item.extractedAddress! : item.address;
if (outputAddress.startsWith('tsp1')) { if (outputAddress.startsWith('tsp1')) {
silentAddresses silentPaymentDestinations
.add(bitcoin.SilentPaymentDestination.fromAddress(outputAddress, outputAmount!)); .add(bitcoin.SilentPaymentDestination.fromAddress(outputAddress, outputAmount!));
} else { } else {
txb.addOutput(addressToOutputScript(outputAddress, networkType), outputAmount!); txb.addOutput(addressToOutputScript(outputAddress, networkType), outputAmount!);
} }
}); });
if (silentAddresses.isNotEmpty) { if (silentPaymentDestinations.isNotEmpty) {
final outpointsHash = bitcoin.SilentPayment.hashOutpoints(outpoints); final outpointsHash = bitcoin.SilentPayment.hashOutpoints(outpoints);
final aSum = bitcoin.SilentPayment.getSumInputPrivKeys(inputPrivKeys); final aSum = bitcoin.SilentPayment.getSumInputPrivKeys(inputPrivKeys);
final generatedOutputs = bitcoin.SilentPayment.generateMultipleRecipientPubkeys( final generatedOutputs = bitcoin.SilentPayment.generateMultipleRecipientPubkeys(
aSum, outpointsHash, silentAddresses); aSum, outpointsHash, silentPaymentDestinations);
generatedOutputs.forEach((recipientSilentAddress, generatedOutput) { generatedOutputs.forEach((recipientSilentAddress, generatedOutput) {
generatedOutput.forEach((output) { generatedOutput.forEach((output) {
final generatedPubkey = output.$1.toHex(); final generatedPubkey = output.$1.toHex();
// TODO: pubkeyToOutputScript (?) // TODO: DRY code: pubkeyToOutputScript (?)
final point = bitcoin.ECPublic.fromHex(generatedPubkey).toTapPoint(); final point = bitcoin.ECPublic.fromHex(generatedPubkey).toTapPoint();
final p2tr = bitcoin.P2trAddress(program: point); final p2tr = bitcoin.P2trAddress(program: point);
txb.addOutput(p2tr.toScriptPubKey().toBytes(), amount); txb.addOutput(p2tr.toScriptPubKey().toBytes(), amount);
@ -400,15 +401,10 @@ abstract class ElectrumWalletBase
txb.addOutput(changeAddress, changeValue); 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++) { for (var i = 0; i < inputs.length; i++) {
final input = inputs[i]; txb.sign(vin: i, amounts: amounts, scriptPubKeys: scriptPubKeys, inputs: inputs);
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);
} }
return PendingBitcoinTransaction(txb.build(), type, return PendingBitcoinTransaction(txb.build(), type,
@ -417,6 +413,11 @@ abstract class ElectrumWalletBase
transactionHistory.addOne(transaction); transactionHistory.addOne(transaction);
await updateBalance(); await updateBalance();
}); });
} catch (e, stacktrace) {
print(stacktrace);
print(e.toString());
rethrow;
}
} }
String toJSON() => json.encode({ String toJSON() => json.encode({
@ -712,9 +713,7 @@ abstract class ElectrumWalletBase
final normalizedHistories = <Map<String, dynamic>>[]; final normalizedHistories = <Map<String, dynamic>>[];
walletAddresses.addresses.forEach((addressRecord) { walletAddresses.addresses.forEach((addressRecord) {
if (addressRecord.address == if (addressRecord.address ==
"tb1pch9qmsq87wy4my4akd60x2r2yt784zfmfwqeuk7w7g7u45za4ktq9pdnmf") { "tb1pch9qmsq87wy4my4akd60x2r2yt784zfmfwqeuk7w7g7u45za4ktq9pdnmf") {}
print(["during fetch txs", addressRecord.address, addressRecord.silentPaymentTweak]);
}
final sh = scriptHash(addressRecord.address, networkType: networkType); final sh = scriptHash(addressRecord.address, networkType: networkType);
addressHashes[sh] = addressRecord; addressHashes[sh] = addressRecord;
}); });

View file

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