• About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us
Coin Snap
  • Home
  • Bitcoin
  • Defi
  • Crypto Mining
  • Crypto News
No Result
View All Result
  • Home
  • Bitcoin
  • Defi
  • Crypto Mining
  • Crypto News
No Result
View All Result
Coin Snap
No Result
View All Result
Home Bitcoin

Bitcoin Core: hacer un script de transferencia USINF Taproot dirección P2TR

luiselduque22 by luiselduque22
August 4, 2025
in Bitcoin
0
189
SHARES
1.5k
VIEWS
Share on FacebookShare on Twitter


Estoy intentando hacer un script de transferencia, para transferir bitcoin desde la dirección a otra

He dado mi script completo a continuación

import * as bitcoin from "bitcoinjs-lib";
import * as tinysecp from "tiny-secp256k1";
import axios from "axios";
import ECPairFactory from "ecpair";

const ECPair = ECPairFactory(tinysecp);
bitcoin.initEccLib(tinysecp);

const NETWORK = bitcoin.networks.testnet;
const MEMPOOL_API = "https://mempool.area/testnet/api";

// Helper perform to validate UTXO
perform validateUtxo(utxo: any): void {
  if (
    !utxo.txid ||
    typeof utxo.vout !== "quantity" ||
    typeof utxo.worth !== "quantity"
  ) {
    throw new Error("Invalid UTXO construction");
  }
  if (!/^(a-fA-F0-9){64}$/.check(utxo.txid)) {
    throw new Error("Invalid UTXO txid format");
  }
}

export async perform sendBTC_P2TR({
  wif,
  recipient,
  amountSats,
}: {
  wif: string;
  recipient: string;
  amountSats: quantity;
}): Promise<{ success: boolean; message: string; txId?: string }> {
  attempt {
    console.log("🏁 Beginning transaction course of...");

    // Enter validation
    if (!wif || !recipient || !amountSats) {
      throw new Error("Lacking required parameters");
    }
    if (typeof amountSats !== "quantity" || amountSats <= 0) {
      throw new Error("Invalid quantity");
    }
    if (!recipient.startsWith("tb1p")) {
      throw new Error("Recipient should be a Taproot testnet deal with");
    }

    // Key derivation
    const keyPair = ECPair.fromWIF(wif, NETWORK);
    if (!keyPair.privateKey) throw new Error("No non-public key derived from WIF");

    const privateKey = keyPair.privateKey;
    const internalPubkey = Buffer.from(
      tinysecp.pointFromScalar(privateKey, true)!.slice(1)
    );

    const p2tr = bitcoin.funds.p2tr({ internalPubkey, community: NETWORK });
    const deal with = p2tr.deal with!;
    const scriptPubKey = p2tr.output!;

    console.log("📬 Sender Taproot deal with:", deal with);

    // Fetch UTXOs
    const { information: utxos } = await axios.get(
      `${MEMPOOL_API}/deal with/${deal with}/utxo`
    );
    if (!utxos.size) return { success: false, message: "No UTXOs discovered" };

    // Estimate charge
    const { information: charges } = await axios.get(
      `${MEMPOOL_API}/v1/charges/really helpful`
    );
    const feeRate = Math.max(charges.hourFee || 1, 2);
    const charge = Math.ceil(feeRate * 110); // Estimated vsize for P2TR

    // Choose UTXO
    const utxo = utxos.discover((u: any) => u.worth >= amountSats + charge);
    if (!utxo)
      return {
        success: false,
        message: `No appropriate UTXO discovered (wanted ${amountSats + charge} sats)`,
      };

    // Key tweaking
    const tweak = bitcoin.crypto.taggedHash("TapTweak", internalPubkey);
    let tweakedPrivKey = tinysecp.privateAdd(privateKey, tweak);
    if (!tweakedPrivKey) throw new Error("Didn't tweak non-public key");

    // Construct PSBT
    const psbt = new bitcoin.Psbt({ community: NETWORK });
    psbt.addInput({
      hash: utxo.txid,
      index: utxo.vout,
      witnessUtxo: { script: scriptPubKey, worth: utxo.worth },
      tapInternalKey: internalPubkey,
    });

    psbt.addOutput({ deal with: recipient, worth: amountSats });
    const change = utxo.worth - amountSats - charge;
    if (change > 294) {
      // Mud restrict
      psbt.addOutput({ deal with, worth: change });
    }

    // Signing (fastened method)
    const tx = (psbt as any).__CACHE.__TX as bitcoin.Transaction;
    const hash = tx.hashForWitnessV1(0, (scriptPubKey), (utxo.worth), 0x00);
    const signature = Buffer.from(tinysecp.signSchnorr(hash, tweakedPrivKey));

    // Replace with correct signature format
    psbt.updateInput(0, {
      tapKeySig: signature,
    });

    // Closing verification
    const validator = (pubkey: Buffer, msghash: Buffer, sig: Buffer) => {
      return tinysecp.verifySchnorr(msghash, pubkey, sig);
    };
    psbt.validateSignaturesOfInput(0, validator);

    psbt.finalizeAllInputs();
    const txHex = psbt.extractTransaction().toHex();

    // Broadcast
    const { information: txId } = await axios.put up(`${MEMPOOL_API}/tx`, txHex, {
      headers: { "Content material-Sort": "textual content/plain" },
    });

    return { success: true, message: "Transaction broadcasted", txId };
  } catch (error: any) {
    console.error("Transaction failed:", error.message);
    return  "Unknown error",
    ;
  }
}

Pero me enfrento a un error que no puedo entender por qué

Transaction failed: Request failed with standing code 400
❌ Transaction failed: sendrawtransaction RPC error: {"code":-26,"message":"mandatory-script-verify-flag-failed (Invalid Schnorr signature)"}

Related articles

Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

August 4, 2025
Paul Atkins de la SEC presenta “Proyecto Crypto” Revolución

Paul Atkins de la SEC presenta “Proyecto Crypto” Revolución

August 4, 2025


Estoy intentando hacer un script de transferencia, para transferir bitcoin desde la dirección a otra

He dado mi script completo a continuación

import * as bitcoin from "bitcoinjs-lib";
import * as tinysecp from "tiny-secp256k1";
import axios from "axios";
import ECPairFactory from "ecpair";

const ECPair = ECPairFactory(tinysecp);
bitcoin.initEccLib(tinysecp);

const NETWORK = bitcoin.networks.testnet;
const MEMPOOL_API = "https://mempool.area/testnet/api";

// Helper perform to validate UTXO
perform validateUtxo(utxo: any): void {
  if (
    !utxo.txid ||
    typeof utxo.vout !== "quantity" ||
    typeof utxo.worth !== "quantity"
  ) {
    throw new Error("Invalid UTXO construction");
  }
  if (!/^(a-fA-F0-9){64}$/.check(utxo.txid)) {
    throw new Error("Invalid UTXO txid format");
  }
}

export async perform sendBTC_P2TR({
  wif,
  recipient,
  amountSats,
}: {
  wif: string;
  recipient: string;
  amountSats: quantity;
}): Promise<{ success: boolean; message: string; txId?: string }> {
  attempt {
    console.log("🏁 Beginning transaction course of...");

    // Enter validation
    if (!wif || !recipient || !amountSats) {
      throw new Error("Lacking required parameters");
    }
    if (typeof amountSats !== "quantity" || amountSats <= 0) {
      throw new Error("Invalid quantity");
    }
    if (!recipient.startsWith("tb1p")) {
      throw new Error("Recipient should be a Taproot testnet deal with");
    }

    // Key derivation
    const keyPair = ECPair.fromWIF(wif, NETWORK);
    if (!keyPair.privateKey) throw new Error("No non-public key derived from WIF");

    const privateKey = keyPair.privateKey;
    const internalPubkey = Buffer.from(
      tinysecp.pointFromScalar(privateKey, true)!.slice(1)
    );

    const p2tr = bitcoin.funds.p2tr({ internalPubkey, community: NETWORK });
    const deal with = p2tr.deal with!;
    const scriptPubKey = p2tr.output!;

    console.log("📬 Sender Taproot deal with:", deal with);

    // Fetch UTXOs
    const { information: utxos } = await axios.get(
      `${MEMPOOL_API}/deal with/${deal with}/utxo`
    );
    if (!utxos.size) return { success: false, message: "No UTXOs discovered" };

    // Estimate charge
    const { information: charges } = await axios.get(
      `${MEMPOOL_API}/v1/charges/really helpful`
    );
    const feeRate = Math.max(charges.hourFee || 1, 2);
    const charge = Math.ceil(feeRate * 110); // Estimated vsize for P2TR

    // Choose UTXO
    const utxo = utxos.discover((u: any) => u.worth >= amountSats + charge);
    if (!utxo)
      return {
        success: false,
        message: `No appropriate UTXO discovered (wanted ${amountSats + charge} sats)`,
      };

    // Key tweaking
    const tweak = bitcoin.crypto.taggedHash("TapTweak", internalPubkey);
    let tweakedPrivKey = tinysecp.privateAdd(privateKey, tweak);
    if (!tweakedPrivKey) throw new Error("Didn't tweak non-public key");

    // Construct PSBT
    const psbt = new bitcoin.Psbt({ community: NETWORK });
    psbt.addInput({
      hash: utxo.txid,
      index: utxo.vout,
      witnessUtxo: { script: scriptPubKey, worth: utxo.worth },
      tapInternalKey: internalPubkey,
    });

    psbt.addOutput({ deal with: recipient, worth: amountSats });
    const change = utxo.worth - amountSats - charge;
    if (change > 294) {
      // Mud restrict
      psbt.addOutput({ deal with, worth: change });
    }

    // Signing (fastened method)
    const tx = (psbt as any).__CACHE.__TX as bitcoin.Transaction;
    const hash = tx.hashForWitnessV1(0, (scriptPubKey), (utxo.worth), 0x00);
    const signature = Buffer.from(tinysecp.signSchnorr(hash, tweakedPrivKey));

    // Replace with correct signature format
    psbt.updateInput(0, {
      tapKeySig: signature,
    });

    // Closing verification
    const validator = (pubkey: Buffer, msghash: Buffer, sig: Buffer) => {
      return tinysecp.verifySchnorr(msghash, pubkey, sig);
    };
    psbt.validateSignaturesOfInput(0, validator);

    psbt.finalizeAllInputs();
    const txHex = psbt.extractTransaction().toHex();

    // Broadcast
    const { information: txId } = await axios.put up(`${MEMPOOL_API}/tx`, txHex, {
      headers: { "Content material-Sort": "textual content/plain" },
    });

    return { success: true, message: "Transaction broadcasted", txId };
  } catch (error: any) {
    console.error("Transaction failed:", error.message);
    return  "Unknown error",
    ;
  }
}

Pero me enfrento a un error que no puedo entender por qué

Transaction failed: Request failed with standing code 400
❌ Transaction failed: sendrawtransaction RPC error: {"code":-26,"message":"mandatory-script-verify-flag-failed (Invalid Schnorr signature)"}

Tags: BitcoincoredirecciónhacerP2TRscriptTaproottransferenciaUSINF
Share76Tweet47

Related Posts

Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

by luiselduque22
August 4, 2025
0

Dubai, EAU, 5 de agosto de 2025 / PRNewswire / - Bybitel segundo cambio de criptomonedas más grande del mundo...

Paul Atkins de la SEC presenta “Proyecto Crypto” Revolución

Paul Atkins de la SEC presenta “Proyecto Crypto” Revolución

by luiselduque22
August 4, 2025
0

Unirse a nuestro Telegrama canal para mantenerse al día sobre la cobertura de noticias de última hora El presidente de...

Respuesta de Irán al bombardeo de EE. UU.: Bitcoin se recupera a medida que se avecina la Primera Guerra Mundial

BTC y ETH con un aspecto bajista en agosto, XRP ve una gran venta de venta: la mejor criptografía para comprar ahora

by luiselduque22
August 3, 2025
0

La liquidación masiva en el paisaje criptográfico hace que la gente se pregunte cuál es la mejor criptografía para comprar...

Arthur Hayes vende $ 13 millones en Ethereum, Pepe y Ethena

Arthur Hayes vende $ 13 millones en Ethereum, Pepe y Ethena

by luiselduque22
August 3, 2025
0

Editorial de confianza Contenido, revisado por expertos líderes de la industria y editores experimentados. Divulgación de anuncios El cofundador de...

Más de 1 m Ethereum retirado de los intercambios en 2 semanas: ¿suministro de choque entrante?

Más de 1 m Ethereum retirado de los intercambios en 2 semanas: ¿suministro de choque entrante?

by luiselduque22
August 3, 2025
0

Ethereum está experimentando una corrección notable después de una manifestación explosiva que vio que su precio aumentara más del 85%...

Load More
  • Trending
  • Comments
  • Latest
Ethereum en la cúspide de una gran ruptura en el primer trimestre de 2025, se espera que las altcoins sigan su ejemplo

Ethereum en la cúspide de una gran ruptura en el primer trimestre de 2025, se espera que las altcoins sigan su ejemplo

December 28, 2024
Raoul Pal califica el patrón gráfico de Ethereum como “uno de los más poderosos en criptografía”, lo que indica que se avecina una gran ruptura ⋆ ZyCrypto

Raoul Pal califica el patrón gráfico de Ethereum como “uno de los más poderosos en criptografía”, lo que indica que se avecina una gran ruptura ⋆ ZyCrypto

December 27, 2024

¿Por qué mi transacción no se confirma y qué puedo hacer al respecto?

July 30, 2025
El impulso alcista impulsa el impulso hacia los $6

El impulso alcista impulsa el impulso hacia los $6

January 7, 2025
¿Ha terminado la temporada de Memecoin? PEPE y SHIB luchan mientras Lunex se eleva

¿Ha terminado la temporada de Memecoin? PEPE y SHIB luchan mientras Lunex se eleva

0
Comprensión de los rendimientos y la economía de las apuestas en Ethereum y Solana

Comprensión de los rendimientos y la economía de las apuestas en Ethereum y Solana

0
Calienta tu hogar mientras ganas Bitcoin con Heatbit

Calienta tu hogar mientras ganas Bitcoin con Heatbit

0
Líderes de IcomTech sentenciados a una década tras las rejas

Líderes de IcomTech sentenciados a una década tras las rejas

0
CFTC explora permitir los intercambios de futuros para ofrecer Bitcoin Spot, Crypto Buying and selling

CFTC explora permitir los intercambios de futuros para ofrecer Bitcoin Spot, Crypto Buying and selling

August 5, 2025
Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

August 4, 2025
Crypto Markets se recupera mientras los inversores miran más allá de las salidas del ETF y el drama de datos de empleos

Crypto Markets se recupera mientras los inversores miran más allá de las salidas del ETF y el drama de datos de empleos

August 4, 2025
Julio de 2025 Progreso laboral: Zen Sechne

Julio de 2025 Progreso laboral: Zen Sechne

August 4, 2025

Coinsnap-Pro

Welcome to CoinSnap Pro, your ultimate destination for everything related to decentralized finance (DeFi), cryptocurrency news, Bitcoin, and crypto mining. Our mission is to keep you informed and empowered in the ever-evolving world of digital assets and blockchain technology.

Categories

  • Bitcoin
  • Crypto Mining
  • Crypto News
  • Defi
  • Economía

Recent News

CFTC explora permitir los intercambios de futuros para ofrecer Bitcoin Spot, Crypto Buying and selling

CFTC explora permitir los intercambios de futuros para ofrecer Bitcoin Spot, Crypto Buying and selling

August 5, 2025
Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

Bybit expande el soporte de USDT0 a HypEvm, Corn y Berachain, desbloqueando el acceso a la establo sin costuras a través de los ecosistemas

August 4, 2025
  • About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us

© 2024 Coinsnap.pro. All rights reserved.

No Result
View All Result
  • Home
  • Bitcoin
  • Defi
  • Crypto Mining
  • Crypto News

© 2024 Coinsnap.pro. All rights reserved.