Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional Flag filterSpent , Needed To Exclude Spent Transaction #68

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
Copy link
Contributor

@notTanveer notTanveer Jan 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think you committed this file by mistake. kindly revert

"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug e2e Test",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"test:e2e",
"--",
"--inspect-brk"
],
"port": 9229,
"console": "integratedTerminal"
}
]
}

11 changes: 5 additions & 6 deletions e2e/helpers/common.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,18 @@ export function generateScanTweakAndOutputEntity(
witness: isWitness
? input.witness.map((v) => v.toString('hex'))
: undefined,
prevOutScript: outputs[index].output.toString('hex'),
prevOutScript: outputs[index].redeem
? outputs[index].redeem.output.toString('hex')
: outputs[index].output.toString('hex'),
};
});
const txouts = transaction.outs.map((output) => ({
scriptPubKey: output.script.toString('hex'),
value: output.value,
}));

const [scanTweak, outputEntity] = new IndexerService().computeScanTweak(
txins,
txouts,
);
const [scanTweak, outputEntity] =
new IndexerService().deriveOutputsAndComputeScanTweak(txins, txouts);

return [scanTweak.toString('hex'), outputEntity];
}
Expand All @@ -47,7 +47,6 @@ export function transactionToEntity(
const entityTransaction = new TransactionEntity();
entityTransaction.blockHash = blockHash;
entityTransaction.blockHeight = blockHeight;
entityTransaction.isSpent = false;
[entityTransaction.scanTweak, entityTransaction.outputs] =
generateScanTweakAndOutputEntity(transaction, outputs);
entityTransaction.id = txid;
Expand Down
165 changes: 144 additions & 21 deletions e2e/helpers/wallet.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,37 @@ import {
networks,
Payment,
Transaction,
crypto,
} from 'bitcoinjs-lib';
import { btcToSats } from '@e2e/helpers/common.helper';
import { randomBytes } from 'crypto';
import { toXOnly } from 'bitcoinjs-lib/src/psbt/bip371';
import { BitcoinRPCUtil } from '@e2e/helpers/rpc.helper';
import { ECPairFactory } from 'ecpair';

initEccLib(ecc);
const ECPair = ECPairFactory(ecc);

export enum AddressType {
P2WPKH = 'P2WPKH',
P2TR = 'P2TR',
P2PKH = 'P2PKH',
P2SH_P2WPKH = 'P2SH_P2WPKH',
}

export type UTXO = {
txid: string;
vout: number;
value: number;
rawTx: string;
addressType: AddressType;
index: number;
};

export type SentTransactionDetails = {
transaction: Transaction;
txid: string;
blockhash: string;
blockHash: string;
};

export class WalletHelper {
Expand Down Expand Up @@ -53,12 +65,18 @@ export class WalletHelper {
return this.bitcoinRPCUtil.mineToAddress(numOfBlocks, walletAddress);
}

async addFundToUTXO(payment: Payment, amount): Promise<UTXO> {
async addFundToUTXO(
payment: Payment,
amount: number,
addressType: AddressType,
index: number,
): Promise<UTXO> {
const txid = await this.bitcoinRPCUtil.sendToAddress(
payment.address,
amount,
);

await this.mineBlock(1);
for (let vout = 0; vout < 2; vout++) {
const utxo = await this.bitcoinRPCUtil.getTxOut(txid, vout);
if (
Expand All @@ -71,6 +89,8 @@ export class WalletHelper {
vout: vout,
value: btcToSats(utxo.value),
rawTx: await this.bitcoinRPCUtil.getRawTransaction(txid),
addressType,
index,
};
}
}
Expand All @@ -80,26 +100,41 @@ export class WalletHelper {
);
}

generateAddresses(count: number, type: 'p2wpkh' | 'p2tr'): Payment[] {
generateAddresses(count: number, type: AddressType): Payment[] {
const outputs: Payment[] = [];
for (let i = 0; i < count; i++) {
const path = `m/84'/0'/0'/0/${i}`;
const child = this.root.derivePath(path);
const child = this.root.derivePath(getDerivationPath(type, i));
let output: Payment;

switch (type) {
case 'p2wpkh':
case AddressType.P2WPKH:
output = payments.p2wpkh({
pubkey: child.publicKey,
network: networks.regtest,
});
break;
case 'p2tr':
case AddressType.P2TR:
output = payments.p2tr({
internalPubkey: toXOnly(child.publicKey),
network: networks.regtest,
});
break;
case AddressType.P2PKH:
output = payments.p2pkh({
pubkey: child.publicKey,
network: networks.regtest,
});
break;
case AddressType.P2SH_P2WPKH:
const p2wpkh = payments.p2wpkh({
pubkey: child.publicKey,
network: networks.regtest,
});
output = payments.p2sh({
redeem: p2wpkh,
network: networks.regtest,
});
break;
default:
throw new Error('Unsupported address type');
}
Expand All @@ -111,18 +146,18 @@ export class WalletHelper {

async craftAndSendTransaction(
utxos: UTXO[],
taprootOutput: Payment,
output: Payment,
outputValue: number,
fee: number,
): Promise<SentTransactionDetails> {
const psbt = new Psbt({ network: networks.regtest });

utxos.forEach((utxo) => {
psbt.addInput({
hash: utxo.txid,
index: utxo.vout,
nonWitnessUtxo: Buffer.from(utxo.rawTx, 'hex'),
});
const keyPair = this.root.derivePath(
getDerivationPath(utxo.addressType, utxo.index),
);
const input = this.createInputFromUtxo(utxo, keyPair);
psbt.addInput(input);
});

const totalInputValue = utxos.reduce(
Expand All @@ -134,15 +169,26 @@ export class WalletHelper {
throw new Error('Insufficient funds');
}

psbt.addOutput({
address: taprootOutput.address,
tapInternalKey: taprootOutput.internalPubkey,
const outputData: any = {
address: output.address,
value: btcToSats(outputValue),
});
};

if (output.internalPubkey) {
outputData.tapInternalKey = output.internalPubkey;
}

psbt.addOutput(outputData);

// Sign the inputs with the corresponding private keys
utxos.forEach((_, index) => {
const keyPair = this.root.derivePath(`m/84'/0'/0'/0/${index}`);
utxos.forEach((utxo, index) => {
let keyPair: any = this.root.derivePath(
getDerivationPath(utxo.addressType, utxo.index),
);

if (utxo.addressType === AddressType.P2TR) {
keyPair = createTaprootKeyPair(keyPair);
}
psbt.signInput(index, keyPair);
});

Expand All @@ -153,8 +199,85 @@ export class WalletHelper {
const txid = await this.bitcoinRPCUtil.sendRawTransaction(
transaction.toHex(),
);
const blockhash = (await this.mineBlock(1))[0];
const blockHash = (await this.mineBlock(1))[0];

return { transaction, txid, blockhash };
return { transaction, txid, blockHash };
}

private createInputFromUtxo(utxo: UTXO, keyPair: BIP32Interface): any {
const input: any = {
hash: utxo.txid,
index: utxo.vout,
};

switch (utxo.addressType) {
case AddressType.P2SH_P2WPKH:
const p2wpkh = payments.p2wpkh({
pubkey: keyPair.publicKey,
network: networks.regtest,
});
const p2sh = payments.p2sh({
redeem: p2wpkh,
network: networks.regtest,
});
input.witnessUtxo = {
script: p2sh.output,
value: utxo.value,
};
input.redeemScript = p2sh.redeem.output;
break;
case AddressType.P2WPKH:
input.witnessUtxo = {
script: payments.p2wpkh({
pubkey: keyPair.publicKey,
network: networks.regtest,
}).output,
value: utxo.value,
};
break;
case AddressType.P2PKH:
input.nonWitnessUtxo = Buffer.from(utxo.rawTx, 'hex');
break;
case AddressType.P2TR:
input.witnessUtxo = {
script: payments.p2tr({
internalPubkey: toXOnly(keyPair.publicKey),
network: networks.regtest,
}).output,
value: utxo.value,
};
input.tapInternalKey = toXOnly(keyPair.publicKey);
break;
}

return input;
}
}

function getDerivationPath(addressType: AddressType, index: number): string {
switch (addressType) {
case AddressType.P2PKH:
return `m/44'/1'/0'/0/${index}`;
case AddressType.P2SH_P2WPKH:
return `m/49'/1'/0'/0/${index}`;
case AddressType.P2WPKH:
return `m/84'/1'/0'/0/${index}`;
case AddressType.P2TR:
return `m/86'/1'/0'/0/${index}`;
default:
throw new Error('Unsupported address type');
}
}

function createTaprootKeyPair(keyPair: BIP32Interface) {
const taprootKeyPair = ECPair.fromPrivateKey(keyPair.privateKey, {
compressed: true,
network: networks.regtest,
});

const tweakedTaprootKey = taprootKeyPair.tweak(
crypto.taggedHash('TapTweak', toXOnly(keyPair.publicKey)),
);

return tweakedTaprootKey;
}
Loading
Loading