What is the process for generating a fresh PSBT transaction using bitcoinjs-lib?

This is the code I've been working on

import * as bitcoin from 'bitcoinjs-lib'
const NETWORK = bitcoin.networks.regtest;
const psbt = new bitcoin.Psbt({ network: NETWORK });

function p2shAddress(node: bitcoin.ECPairInterface): string {
  const ecpair = bitcoin.ECPair.fromPublicKey(node.publicKey, { network: NETWORK });
  const p2wpkh = bitcoin.payments.p2wpkh({ pubkey: ecpair.publicKey, network: NETWORK });
  const p2sh = bitcoin.payments.p2sh({ redeem: p2wpkh });
  return p2sh.address as string;
}

const tx = '02000000000105e11d8c7970aff25a8a431c49397316ce80af25dca6ac395f172e2d7326d42e570100000017160014cccb96f2ec1b5a2b7081f96b78077488769e3d8efeffffff77bcf72d69888cc739341107028e1e8a302d507fe9ffb94c5359fb1e82f08f370100000017160014527aef9caa6e0a12ecea8ce255cb36427a2f451afeffffff3cad9140403d6ec68bc0cf0b261daa4a41d92f04bddad98fc05a305127c7145c00000000171600143ea2fa276d3de26e4e220a1e6d343a235edbaff6feffffff250152b93632b8e275aba954c894dcbc2c0124a5c1db10de3ed...
// this is the raw-tx I sent to 2NFJUYmdpAPRoo6qqUZem7rmBq2QSSPKBPu.
// did I understand it wrong, and this is not the supposed to be nonWitnessUtxo?

psbt.addInput({
  hash: '25ba0c45cadf92ded94432101d286975dcdb865df44b68da597910ea783cff74',
  index: 0,
  nonWitnessUtxo: Buffer.from(tx, 'hex'),
});
psbt.addOutput({
  address: '2MuhtGHkdxiL4BjFAAaYjq8Q2mwnCoYSebt',
  value: 4000,
});
const signer = bitcoin.ECPair.fromPrivateKey(Buffer.from('64e897b5fac936a30a7a73e1c2892697c91b0705a8d061ea28e59f41d2876e0d', 'hex'), { network: NETWORK });
console.log({ address: p2shAddress(signer) });
// { address: '2NFJUYmdpAPRoo6qqUZem7rmBq2QSSPKBPu' }
psbt.signInput(0, signer);
psbt.validateSignaturesOfInput(0, signer.publicKey);

An error keeps popping up stating:

The key 02c4ac... cannot sign for this input

I have double-checked by decoding the transaction using

bitcoin-cli decoderawtransaction $TX
and confirmed that the address in the first vout (index 0) matches the one generated by p2shAddress(signer), which is
2NFJUYmdpAPRoo6qqUZem7rmBq2QSSPKBPu
.

Can anyone help me identify where the mistake might be?

Answer №1

Since the utxo input contains a p2sh address, a redeemScript field is required for the input:

const node = signer;
const ecpair = bitcoin.ECPair.fromPublicKey(node.publicKey, { network: NETWORK });
const p2wpkh = bitcoin.payments.p2wpkh({ pubkey: ecpair.publicKey, network: NETWORK });

psbt.addInput({
  hash: '25ba0c45cadf92ded94432101d286975dcdb865df44b68da597910ea783cff74',
  index: 0,
  nonWitnessUtxo: Buffer.from(tx, 'hex'),
  redeemScript: p2wpkh.output
});

I trust this clarifies things!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Numerous points highlighted on the map

As I develop my application, I am working on setting up an event to automatically load data from a CSV excel file for display. My goal is to extract information from the Excel CSV file and use it to populate locations on a Google Map within my application ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

When utilizing the File System Access API, the createWritable() method functions perfectly within the console environment but encounters issues when executed

I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code: const writable = await fileHandle.createWritab ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

Utilizing the power of Datatables through AJAX calls with HTML Forms

Hello, I am currently working on incorporating djangorestframework-datatables with the datatables' JQuery plugin. My task involves loading a large table (consisting of approximately 15000 entries, paginated) with the serverSide option enabled. Enabli ...

The function message.react in Discord.js is throwing an error

I have a Discord bot set up for reaction roles. I use IDs to cache the messages that need reactions and make sure the bot reacts with the appropriate emojis before further action. Here is my process for caching the messages: const guild = await client.guil ...

Using vue-resource to intercept an ajax error and catching the "Uncaught (in promise)" exception

I am utilizing vue-resource to retrieve data from the server. In order to access the correct data, a user must possess a JWT token. If the token is invalid or has expired, a status code of 401 will be returned. Similarly, if a user attempts to reach a forb ...

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...

Is there a way to integrate Prettify with Blogger/BlogSpot?

I am currently utilizing blogger.com as a platform to showcase programming texts and I am interested in incorporating Prettify (similar to Stack Overflow) to enhance the appearance of my code samples. What is the best method for installing the Prettify sc ...

Keep only certain fields and eliminate the rest

Write a function that filters out all fields except 'firstName' and 'lastName' from the objects. Check out this code snippet I came up with. Any feedback? let people = [ { firstName: 'John', lastName: &apo ...

Handling Errors with Symfony 5 JSON Responses and VueJS Using Axios for Customized Error Messages

I need to show a personalized error message when my JSON response throws an error. Some of my services trigger an error like this: if (count($recipients) === 0) { throw new TransportException($this->carrierService::ERROR_NO_MAIL_ADDRESSES); } The ...

Real-time update of quiz results based on varying factors

In my quiz, I have set up variables that start at 0 and increase based on certain conditions. One variable should increase when a question is answered correctly, while the other should increase when a question is answered incorrectly. If you answer a quest ...

Having trouble accessing the downloaded file from S3 using Angular and NodeJS

Currently, I am facing an issue while attempting to download a jpg image from amazon S3 using the NodeJs SDK. Although I can successfully retrieve the file object on the backend, encountering difficulties arises when trying to create a blob object and down ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

The Array Find() method keeps returning 'undefined' when trying to search for data based on URL parameters

Is there a way to display data from an array based on a specific condition? I have been attempting to do this by checking if the requested id matches any of the ids in the data array. Unfortunately, whenever I run the following code snippet, I always end u ...

Control the button's activation status by accepting or unaccepting the two checkbox conditions

In my search through stackoverflow for help on enabling/disabling a button conditionally, I found some assistance but nothing quite matched what I needed. My situation involves two checkbox conditions rather than just one. The button should only be enable ...

Selecting a full table row activates a top-up popup

I have successfully implemented a script in Javascript to enable full table row selection as shown below. <script type="text/javascript"> $(function() { $('#link-table td:first-child').hide(); $('#link-table tr').hover(func ...

Press on the row using jQuery

Instead of using link-button in grid-view to display a popup, I modified the code so that when a user clicks on a row, the popup appears. However, after making this change, nothing happens when I click on a row. Any solutions? $(function () { $('[ ...

Updating the JSON format output from snake case to camel case in a React web application

Modifying JSON output in a React Web app to change keys from snake case to camel case Currently, the API endpoint response is structured like this: [ { "id": 1, "goals_for": 0, "goals_against": 0, "points": 0 } ] ...