GithubHelp home page GithubHelp logo

antonilol / btc_stuff Goto Github PK

View Code? Open in Web Editor NEW
12.0 3.0 2.0 389 KB

Bitcoin transaction examples with bitcoinjs-lib

License: MIT License

JavaScript 15.16% HTML 2.14% Shell 0.28% TypeScript 82.41%
bitcoin js p2sh p2wsh p2sh-p2wsh bitcoinjs-lib blockchain ecdsa ts

btc_stuff's Introduction

btc_stuff

Bitcoin transaction examples with bitcoinjs-lib

This is a collection of scripts with various aspects of bitcoin tech (mostly scripts) in TypeScript and/or JavaScript.
When dealing with TypeScript files, run npm run build before running them with node <file>, or use ts-node <file>.

(!) Use at your own risk, only use on the mainnet if you are 100% certain it works the way you want or funds can be lost! (!)

Developed mostly using Bitcoin Core v23, some older ones could expect v22 RPCs

Example usage

Note: this example still works for some files, but is subject to change

Requirements: Make sure to have

  • a bitcoin node synced and running on the desired network/networks
  • bitcoin-cli working
  • nodejs and npm installed and working

Clone this repository, cd into it and install npm dependencies.

git clone https://github.com/antonilol/btc_stuff.git
cd btc_stuff
npm install

Choose a script you want to start with. I will use p2sh.js here.

Edit something (optional), for example: change OP_13 to OP_12.

Run it

Most scripts will either output a locking script or an address, in this case it is a locking script, so put this locking script in Bitcoin Core's decodescript rpc.

$ bitcoin-cli -testnet decodescript 935c87
{
  "asm": "OP_ADD 12 OP_EQUAL",
  "type": "nonstandard",
  "p2sh": "2N9h3wvypp2oLaaGfHiDVix5GSeTPMGnhQv",
  "segwit": {
    "asm": "0 a5d2c3f6d91680a99d36ef8ba054a57ab220520f7ebe93ddb56316f85f292315",
    "hex": "0020a5d2c3f6d91680a99d36ef8ba054a57ab220520f7ebe93ddb56316f85f292315",
    "address": "tb1q5hfv8akez6q2n8fka796q49902ezq5s006lf8hd4vvt0shefyv2sw96epz",
    "type": "witness_v0_scripthash",
    "p2sh-segwit": "2NCqyYd7K5K9pj6SiUXV65NV5baZNvtfxPE"
  }
}

We will be using the address next to p2sh: 2N9h3wvypp2oLaaGfHiDVix5GSeTPMGnhQv.

Send some sats to this address, 1000 for example:

$ bitcoin-cli -testnet sendtoaddress 2N9h3wvypp2oLaaGfHiDVix5GSeTPMGnhQv 0.00001000
ae70f2d7625184471c9bbf3dea64febc5b562131f2b7c6ccbf3125d493402ac1

This will give a TXID, look this up on a block explorer to find out where the desired output is.

You need to look for the output index, where the output with this P2SH address is, counting from zero.

(If it is the first output, the output index is 0, if it is the second, it is 1 and so on.)

Now go back to your editor and put the TXID and the output index in.

It will look like this:

const txid = 'ae70f2d7625184471c9bbf3dea64febc5b562131f2b7c6ccbf3125d493402ac1'; // txid hex here
const vout = 1;

We also need to change the input script because we changed the value from 13 to 12.

The script OP_ADD 12 OP_EQUAL expects 2 numbers that add up to 12, i will chose 4 and 8 here.

tx.setInputScript(0, bitcoin.script.compile([
	bitcoin.opcodes.OP_4,
	bitcoin.opcodes.OP_8,
	redeemScript
]));

Some other values need to be set too, like input_sat to how much sats you sent to the address, fee_sat to how much fee you want to pay and put your own receiving address of a wallet over the placeholder tb1qbech32addresshere.

Now by running the script it should create and broadcast your transaction and print its TXID to the console. This TXID can also be looked up in a block explorer. (mempool.space and blockstream.info have a Details button to show advanced details about scripts.)

If you have any questions, found bugs or have an improvement/addition feel free to submit it in either issues, discussions or pull requests.

Network

Almost all scripts by default use testnet. To use another network (for example mainnet):

add

setChain('main'); // Where 'main' can be replaced by 'test', 'signet' or 'regtest'

(setChain may need to be imported from ./btc.js)

and if applicable (not all script use bitcoinjs-lib), change

const network = bitcoin.networks.testnet;

to

const network = bitcoin.networks.bitcoin; // Where bitcoin can be replaced by testnet or regtest.
                                          // For signet, use testnet (they use the same address prefix).

btc_stuff's People

Contributors

antonilol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

btc_stuff's Issues

How to redeem UTXO with P2SH

I had to send utxo from p2pkh to p2sh address, here is my code .

const bitcoin = require('bitcoinjs-lib');
const ecc = require('tiny-secp256k1');
const ecpair = require('ecpair');
const { buffer } = require('stream/consumers');

const TESTNET = bitcoin.networks.testnet;
const ECPair = ecpair.ECPairFactory(ecc);

const alice = ECPair.fromWIF(
    'xxx',
);

const address = bitcoin.payments.p2pkh({
    pubkey: alice.publicKey,
    network: TESTNET,
});


console.log("alice address", address.address);




const tx = new bitcoin.Transaction(TESTNET);



const txId = "c1e48b3ae44001fb1dddf2958b177ace2c640ce636c32860c85b82431fa3eb13";
const vout = 0;


tx.addInput(Buffer.from(txId, 'hex').reverse(), vout);

// 
// const sha256HashString = bitcoin.crypto.sha256(Buffer.from('Btrust Builders')).toString('hex');


const lockingScript = bitcoin.script.compile([
    bitcoin.opcodes.OP_ADD,
	bitcoin.opcodes.OP_13,
	bitcoin.opcodes.OP_EQUAL
]);


const decompiled = bitcoin.script.decompile(Buffer.from(lockingScript, 'hex')).toString('hex');
console.log('Decompiled Redeem Script:', decompiled);

const p2shAddress = bitcoin.payments.p2sh({
    redeem: { output: lockingScript },
    network: TESTNET
});

console.log('p2shAddress :', p2shAddress.address);


// 
// const outputValue = utxo.value - FEE; // 
tx.addOutput(
    bitcoin.address.toOutputScript(p2shAddress.address, TESTNET),
    800
);

console.log("output ScriptPubKey (HEX)", bitcoin.address.toOutputScript(p2shAddress.address, TESTNET));
const outputScript = bitcoin.address.toOutputScript(p2shAddress.address, TESTNET);
const asmCode = bitcoin.script.toASM(outputScript);
console.log('Output Script ASM:', asmCode);

// 
const hashType = bitcoin.Transaction.SIGHASH_ALL;



const utxoAddress = bitcoin.payments.p2pkh({ pubkey: alice.publicKey, network: TESTNET });
const p2pkhScriptPubKey = bitcoin.address.toOutputScript(utxoAddress.address, TESTNET); //
console.log('toOutputScript',p2pkhScriptPubKey);

const signatureHash = tx.hashForSignature(0, p2pkhScriptPubKey, hashType); // 
console.log("signatureHash",signatureHash.toString('hex'));


const signature = bitcoin.script.signature.encode(alice.sign(signatureHash), hashType);
console.log("signature",signature.toString('hex'));
const scriptSig = bitcoin.script.compile([
  signature,
  alice.publicKey  
]);


console.log("scriptSig",scriptSig.toString('hex'))   //

tx.setInputScript(0, scriptSig);

console.log('Tx Hex:', tx.toHex());

and then I want unlocking this utxo from p2sh tp p2pkh, here is my code

const bitcoin = require('bitcoinjs-lib');
const ecc = require('tiny-secp256k1');
const ecpair = require('ecpair');


const TESTNET = bitcoin.networks.testnet;
const ECPair = ecpair.ECPairFactory(ecc);

const alice = ECPair.fromWIF(
    'xxx',
);

const address = bitcoin.payments.p2pkh({
    pubkey: alice.publicKey,
    network: TESTNET,
});

console.log("alice address", address.address);


// 找到P2SH输出对应的UTXO
const p2shUtxo = {
    txId: "94b5a43de760c4e88c25a7b3642174d5e52a9b5b9334997ce4a50d2b2f8cefec",
    outputIndex: 0,
    address: "2ND8PB9RrfCaAcjfjP1Y6nAgFd9zWHYX4DN",
    value: 300
};



const pubKeyHash = bitcoin.crypto.hash256(alice.publicKey);
console.log("pubKeyHash",pubKeyHash);


const unlockingScript = bitcoin.script.compile([
    bitcoin.opcodes.OP_6,
	bitcoin.opcodes.OP_7,
    bitcoin.opcodes.OP_ADD,
	bitcoin.opcodes.OP_13,
	bitcoin.opcodes.OP_EQUAL

]);

// const data = Buffer.from('Btrust Builders');
const redeemTx = new bitcoin.Transaction(TESTNET);
redeemTx.addInput(Buffer.from(p2shUtxo.txId, 'hex').reverse(), p2shUtxo.outputIndex);
redeemTx.addOutput(bitcoin.address.toOutputScript(address.address, TESTNET), p2shUtxo.value);
// console.log(bitcoin.address.toOutputScript(address.address, TESTNET))  
redeemTx.setInputScript(0, unlockingScript);
console.log('Redeem Tx Hex:', redeemTx.toHex());

When I want broad the hex ,"0100000001ecef8c2f2b0da5e47c9934935b9b2ae5d5742164b3a7258ce8c460e73da4b59400000000055657935d87ffffffff012c010000000000001976a914b163d850125f1b65eadbcf15f88b7ef16836c1ee88ac00000000" I got error mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)

I can make sure my txid and vout is right. How can I solve this problem , thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.